#discord-bots

1 messages ยท Page 228 of 1

fiery salmon
#

U could always use a shortner

zealous jay
#

maybe

fiery salmon
outer parcel
#

Hi hope everyone is doing well im trying to create a welcome message whenever someone joins server, i know how to create this and i created it like i usually do ,

but whenever someone joins nothing happens at all

ofc i checked my intents but my intents were all enabled so im confused to as why the bot is not picking up whenever someone joins

fiery salmon
outer parcel
#

this is my client initialisation code

zealous jay
#

url shorteners dont seem to work with these type of urls

outer parcel
zealous jay
#

I guess I'll have to use the long url

hushed galleon
#

depends on the library, in discord.py you'd use the tasks.loop(time=) argument
seems nextcord has it too, but assumes naive datetimes are in UTC

outer parcel
#

[here](your_link_goes_here)

#

so if you want to hyperlink https://youtube.com

zealous jay
outer parcel
#

nvm

zealous jay
#

haha

outer parcel
#

i never read that mb

zealous jay
#

its okay, thanks

outer parcel
zealous jay
#

its not a website

#

its an url that opens a server on a game

fiery salmon
outer parcel
#

oh

hushed galleon
outer parcel
outer parcel
fiery salmon
outer parcel
zealous jay
#

no problem

hushed galleon
elder kettle
#

Whats the problem here

outer parcel
elder kettle
hushed galleon
#

can you show the rest of your code? the problem might be somewhere else

#

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

elder kettle
#

And your every linked account have same name

outer parcel
cold sonnet
outer parcel
#

nothing

elder kettle
cold sonnet
#

don't change_presence on_ready

outer parcel
#

that is why i put print()

outer parcel
outer parcel
cold sonnet
#

lemme get that tag

outer parcel
cold sonnet
#

Don't change_presence (or make API calls) in on_ready within your Bot or Client.
Discord has a high chance to completely disconnect you during the READY or GUILD_CREATE events (1006 close code) and there is nothing you can do to prevent it.

Instead set the activity and status kwargs in the constructor of these Classes.

bot = commands.Bot(command_prefix="!", activity=..., status=...)

As noted in the docs, on_ready is also triggered multiple times, not just once.

Basically: don't ๐Ÿ‘ do ๐Ÿ‘ shit ๐Ÿ‘ in ๐Ÿ‘ on_ready.

elder kettle
outer parcel
#

ok ill try changing tthat

naive briar
elder kettle
cold sonnet
#

dunno why everyone does the same shit in on_ready

#

is this in a youtube tutorial

outer parcel
#

if you look i said at beginningprint("someone joined"

#

but nothing is printed meaning bot does not realise someone joined

elder kettle
naive briar
elder kettle
#

Im not much familier

naive briar
#

I've always been wondering

smoky sinew
#

should i use == or is on ChannelType?

cold sonnet
#

you use it for like a print

naive briar
#

@outer parcel show the whole code then it'd be clearer

cold sonnet
elder kettle
#

Yeah

#

I knew

elder kettle
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.

outer parcel
#

pasted

elder kettle
outer parcel
naive briar
#

Oops, forgor to turn off reply

cold sonnet
#

he forgor

outer parcel
#

if u say guild id

naive briar
#

You're overriding the variable

outer parcel
#

oh

#

OHHHH

#

I JUST REALISED im acc dumb

hushed galleon
# smoky sinew should i use `==` or `is` on ChannelType?

both will work in this case as long as you're comparing the enum member itself, which is basically a necessity for a regular Enum subclass
where it does matter is if its a mixin for another class like IntEnum, and you're attempting to compare an instance of a different type ```py

class MyEnum(enum.IntEnum):
... FIRST = 1
...
MyEnum.FIRST is MyEnum.FIRST, MyEnum.FIRST == MyEnum.FIRST
(True, True)
MyEnum.FIRST is 1, MyEnum.FIRST == 1
(False, True)```

outer parcel
#

ty so much

smoky sinew
#

i see

fading egret
#
@app_commands.command(
        name="test",
        description="test")
    async def test(self, interaction: discord.Interaction):
        data = range(1, 20)
        pagination_view = PaginationView()
        pagination_view.data = data
        await pagination_view.send(interaction) ```

```py
    async def send(self, interaction: discord.Interaction):
        self.message = await interaction.followup.send("test")

discord.app_commands.errors.CommandInvokeError: Command 'paginate' raised an exception: NotFound: 404 Not Found (error code: 10015): Unknown Webhook

have i made an error in the constructor of the send function?
does it not find the interaction?

smoky sinew
#

you didn't defer it first

#

you have to defer it to send a follow up, or just use interaction.response.send_message

slate swan
#

Also the error points to paginate command and you show the test command code

fading egret
smoky sinew
#

use Interaction.original_response i think

#

If the interaction response was a newly created message (i.e. through InteractionResponse.send_message() or InteractionResponse.defer(), where thinking is True) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).

fading egret
solar quail
#
import os
import discord
import requests
import json
import random

intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print('Logged in as {0.user}'.format(client))

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

    if message.content.startswith('!trivia'):
        response = requests.get("https://opentdb.com/api.php?amount=1&type=multiple")
        data = json.loads(response.text)
        question = data['results'][0]['question']
        answers = data['results'][0]['incorrect_answers'] + [data['results'][0]['correct_answer']]
        random.shuffle(answers)

        trivia_embed = discord.Embed(title="Trivia", description=question, color=discord.Color.blue())
        trivia_embed.add_field(name="Options:", value="\n".join(answers), inline=False)

        await message.channel.send(embed=trivia_embed)
#

for some reason its not responding without errors

slate swan
#

Then what are the errors

solar quail
#

there isn't any

slate swan
#

You said there are joeCollapse

solar quail
#

i said without

#

without errors

slate swan
#

you put not before it

pliant gulch
#

Try putting on message intents both via gateway & the bot constructor

solar quail
#

thank you

slate swan
#

Yeah you need message_content intent enabled

#

!d discord.Intents.message_content

unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

โ€ข The message was sent by the client

โ€ข The message was sent in direct messages

โ€ข The message mentions the client

This applies to the following events...

solar quail
#
import os
import discord
import requests
import json
import random

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

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print('Logged in as {0.user}'.format(client))

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

    if message.content.startswith('!trivia'):
        response = requests.get("https://opentdb.com/api.php?amount=1&type=multiple")
        data = json.loads(response.text)
        question = data['results'][0]['question']
        answers = data['results'][0]['incorrect_answers'] + [data['results'][0]['correct_answer']]
        random.shuffle(answers)

        trivia_embed = discord.Embed(title="Trivia", description=question, color=discord.Color.blue())
        trivia_embed.add_field(name="Options:", value="\n".join(answers), inline=False)

        await message.channel.send(embed=trivia_embed)
#

so would this work?

fading egret
#

so i need to define in a way the message so i can edit it in another function

slate swan
solar quail
#

oh oops lol

#

ok so it responds to the start command but stops after that

solar quail
#
import asyncio
import os
import discord
import requests
import json
import random
import traceback

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

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print('Logged in as {0.user}'.format(client))

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

        if message.content.startswith('!trivia'):
            response = requests.get("https://opentdb.com/api.php?amount=1&type=multiple")
            data = json.loads(response.text)
            question = data['results'][0]['question']
            answers = data['results'][0]['incorrect_answers'] + [data['results'][0]['correct_answer']]
            correct_answer = data['results'][0]['correct_answer']
            random.shuffle(answers)

            trivia_embed = discord.Embed(title="Trivia", description=question, color=discord.Color.blue())
            trivia_embed.add_field(name="Options:", value="\n".join(answers), inline=False)

            await message.channel.send(embed=trivia_embed)
    except Exception as e:
        traceback.print_exc()

        def check_answer(m):
            return m.author != message.author and m.content.lower() == correct_answer.lower()

        try:
            user_answer = await client.wait_for('message', check=check_answer, timeout=15.0)
        except asyncio.TimeoutError:
            await message.channel.send(f"Time's up! THe correct answer is {correct_answer}.")
        else:
            await message.channel.send(f"Correct! The answer is {correct_answer}.")

client.run('YOUR-TOKEN-HERE')
slate swan
unkempt canyonBOT
#

await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the original interaction response message.

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

This method is also the only way to edit the original message if the message sent was ephemeral.
solar quail
#

its not responding after the initial question

smoky sinew
tall temple
#

i want to attribute to the file name the guild id where the command will be executed

outer parcel
#

Ok im creating a level up command and everything works only problem is

i searched up problem and i assumed i needed to do await client.process_commands()
but this did not work since process_command is not a thing anymore?

#

how would i do this now

smoky sinew
#

it's discord.ext.commands.Bot.process_commands

stone palm
#

it does not print anything after 5 for some reason```py
print("5")
channel=guild.get_thread(approved_papers_channel)
print("a")

#

no errors

tall temple
slate swan
#

!dashm

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

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

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

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

tall temple
slate swan
#

on windows its usually py -m

#

instead of python -m

tall temple
#

๐Ÿซ‚

vapid grove
#

Is there a specific function that waits for user to click the button before proceeding?

hushed galleon
#

from a view? sure, use .stop() in the callback and .wait() to wait for the view to stop/timeout

thin raft
#

can you remove these logs?

fading egret
#

which is the best sql database for a discord bot?

smoky sinew
#

postgres or sqlite if your bot is small

#

it comes down to personal preference really @fading egret

fading egret
outer parcel
#

because it is asking me for them

cold sonnet
#

leave out message=

#

and use client instead of commands.Bot

outer parcel
#

i did this

cold sonnet
#

actually client doesn't have commands unless you did client = commands.Bot() in the beginning of your code

outer parcel
outer parcel
#

hence why i used commands.Bot

cold sonnet
#

yeah use client instead of commands.Bot

outer parcel
#

i tried

#

but client.process_commands() is not a thing

cold sonnet
#

you need an object to call process_commands on

outer parcel
#

for my code

cold sonnet
outer parcel
cold sonnet
#

so you defined client twice...

outer parcel
#

i defined client in beginning

#

then redefined it after it has got ready

cold sonnet
#

you don't need client = commands.Bot() at all

#

check this out

outer parcel
#

o

cold sonnet
#

!e

variable = "Hello"
variable = "World!" 
print(variable) ```
unkempt canyonBOT
#

@cold sonnet :white_check_mark: Your 3.11 eval job has completed with return code 0.

World!
outer parcel
#

i see

cold sonnet
#

setting variable to "Hello" did nothing

#

๐Ÿ‘๐Ÿฟ

outer parcel
#

how does it fix this thou

cold sonnet
#

since client doesn't have commands

#

cuz it can't have commands

#

you don't need to process commands

smoky sinew
#

you need a Bot instance

smoky sinew
smoky sinew
cold sonnet
#

if you saw their code he redefined it

outer parcel
#

i need to process

smoky sinew
cold sonnet
#

you're telling me he made a commands.Bot instance and proceeded to subclass discord.Client to use that subclass in the same code

outer parcel
#

if i try client.process_commands()

cold sonnet
#

probably slow af

smoky sinew
outer parcel
cold sonnet
#

slash commands

outer parcel
#

These are all my code related to client

outer parcel
cold sonnet
#

those aren't message commands

#

technically they're not messages

smoky sinew
#

prefix commands

#

message commands are the context menu commands you get when right-clicking a message

#

like with sir lancebot

outer parcel
#

o

cold sonnet
#

thanks

outer parcel
#

but actually no command is appearing

cold sonnet
#

since when can you make stuff like that

smoky sinew
#

they are technically slash commands internally

cold sonnet
outer parcel
#

so how would i fix?

smoky sinew
#

@outer parcel decide if you want prefix commands (e.g. !help) in your bot

outer parcel
#

no

smoky sinew
#

remove process_commands and remove this part:

cold sonnet
#

man put a yellow thumbsup so it's not just my black thumbsup reaction

outer parcel
#

ok

#

ty

#

i got this error

cold sonnet
#

show command

outer parcel
#

i think it has to do with this inside of level command

#

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

outer parcel
cold sonnet
#

paste the traceback too

outer parcel
#

thing is

outer parcel
#

ye so i found error

#

its only wrong with this level command because im using async with client.db.cursor() as cursor

cold sonnet
#

I'd suggest closing that async with statement as soon as you don't use your database anymore

#

but I don't actually know why you get that error

outer parcel
#

im not this acquainted with it

cold sonnet
#

that would mean deindenting the try-except

#

and everything below

outer parcel
#

tried that

#

same error

#

it seems that coroutine can not be reused

slate swan
#

Hey, im trying to make modlogs & its giving me this error with webhooks.

Webhook views require an associated state with the webhook 
smoky sinew
smoky sinew
slate swan
smoky sinew
#

what's your code

outer parcel
smoky sinew
#

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

outer parcel
#

this section causing problem

smoky sinew
#

paste it please

outer parcel
smoky sinew
#

i don't think you await fetchone

#

oh wait you do

#

are you using aiosqlite?

slate swan
#
async with aiohttp.ClientSession() as session:
                            webhook = Webhook.from_url('', session=session)
                            xx = await to_object(str(ce))
                            await webhook.send(**xx)```
the to_object is my embed parser to split things & make them an embed. currently the `ce` variable has {content: test}. this will send the message in a regular message. but it gives me that error

@smoky sinew
outer parcel
smoky sinew
outer parcel
#

and saw again and it says error is here

slate swan
smoky sinew
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.

outer parcel
smoky sinew
#

what

#

what even is this

#

you are trying to send buttons though

slate swan
smoky sinew
#

yes you are

#

you're creating an empty view and then passing it to be sent to the webhook

slate swan
#

hm

smoky sinew
#

webhooks cannot send views

#

because they have no way of receiving interactions from them

#

even URL buttons i'm pretty sure

slate swan
#

hm. i see

outer parcel
#

if i run command it works

#

but if i run it again it does not

#

because it is repeating the command again for same image

worthy pebble
#

what is the application/website that creates bots through Python?

tender mantle
#

i have noticed i can't link to an .ico files for the avatar_url in an embed, is there a way to get around that?

hushed galleon
vivid axle
#

does anyone know a way i can get a list of commands, im using discord.py

#

in the code not discord

#

i found

#

bot.commands

latent sonnet
#

!e print("test")

unkempt canyonBOT
#

@latent sonnet :white_check_mark: Your 3.11 eval job has completed with return code 0.

test
vivid axle
#

does anyone know how i can organise commands into separate files like discord.js?

oblique axle
#

use cogs

naive briar
#

It's called extension

vivid axle
smoky sinew
#

they meant extensions though

vivid axle
#

but i meant to put each command in a file

#

would i make a cog for each command

oblique axle
#

You can import the file with cog

#

Then add the cog

smoky sinew
#

that's not really good practice

vivid axle
#

ok

smoky sinew
#

you should have multiple commands in one cog

vivid axle
smoky sinew
#

you are being misleading

vivid axle
#

thank you mud kip

oblique axle
#

Sorry

smoky sinew
#

you shouldn't import cogs that's what extensions are for in the first place

vivid axle
#

sorry i just did discord.js before and i was wondering if it was posible

white peak
#

this channel is for asking some questions right

smoky sinew
#

yes

white peak
#

so uh

vivid axle
white peak
#

i did a code thats like uh
if message.content.startswith('!hello'):
await message.channel.send('Hello!')
but the bot dont respond(its online)

vivid axle
#

it needs message content intent

#

right?

naive briar
#

Yes?

#

!d discord.Intents.message_content

unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

โ€ข The message was sent by the client

โ€ข The message was sent in direct messages

โ€ข The message mentions the client

This applies to the following events...

vivid axle
#

:O

smoky sinew
#

good job

white peak
#

what happened

mossy bluff
#

im assuming not

white peak
#

a

white peak
#

thats what i thought

mossy bluff
white peak
#

yea

#

not in 100+

mossy bluff
#

ok

smoky sinew
#

you have to enable it with code

mossy bluff
#

oh yeah

white peak
smoky sinew
#

!d discord.Intents.message_content

unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

โ€ข The message was sent by the client

โ€ข The message was sent in direct messages

โ€ข The message mentions the client

This applies to the following events...

smoky sinew
#

set this to True

mossy bluff
#
    intents = discord.Intents.default()
    intents.message_content = True
    client = discord.Client(intents=intents)```
smoky sinew
mossy bluff
#

yeah he might not be

white peak
#

naw

#

my stuff lagged

#

hol on

mossy bluff
#

@white peak wait arent you in my bots server?

white peak
#

oh yea im using default

mossy bluff
mossy bluff
#

the yba bot server

#

i own that server lol

white peak
#

oh

#

you own that

mossy bluff
#

yeah

white peak
#

nice

raven steeple
#

i found code on github who can try run it i need it for my business

#

ican pay

jagged adder
#

Does anyone have any good sources to look at for generating images within python? Iโ€™m trying to create an image that represents location on a map, and I want to use co-ords or some such instead of 100 images and if/else statements etc. I want to be then be able to send said pic within a discord channel or dm

smoky sinew
jagged adder
#

Iโ€™ve never used that before, any tips

#

And can u clarify what u mean by an executor

smoky sinew
#

!d asyncio.loop.run_in_executor

unkempt canyonBOT
#

awaitable loop.run_in_executor(executor, func, *args)```
Arrange for *func* to be called in the specified executor.

The *executor* argument should be an [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor "concurrent.futures.Executor") instance. The default executor is used if *executor* is `None`.

Example:
smoky sinew
#

you can just open a base image and overlay another image at whatever location you need

#

then save that to a temporary file and send it to discord

vocal snow
smoky sinew
#

i'm going to unrandom your memory

jagged adder
#

So Iโ€™m basically needing 2 images ?

#

Guess Iโ€™ll have to do some reading lol

smoky sinew
#

overlay one on top of the other

jagged adder
#

Is there a way for it to be a bit more flexible?

#

So I donโ€™t need the second image

#

I guess it needs to know whatโ€™s where โ€ฆ

upbeat ice
#

Anything is possible. All you need is objective requirements

naive briar
#

Not everything is possible

smoky sinew
#

literally just do whatever you want

#

it was just a suggestion as to how you could do it

#

i don't even know what you're making

jagged adder
#

yeah ive been having a read

#

on the docs

#

im making a text adventure discord bot and i just wanted to be able to include a visual representation with a "You are here" arrow where the player is at the point in time

jagged adder
smoky sinew
#

and place it somewhere on the image and optionally rotate it

jagged adder
#

w Pillow ?

smoky sinew
#

yes

jagged adder
#

ah yeah

#

ive got pillow installed, gonna mess around w it and a test image, see how easy it is

smoky sinew
#

in it

#

because the command is in a cog

#

so you put the function in a cog

drifting arrow
#

How do you @ channels?
<@#1097084154400743465> is wrong apparently lol

#

nvm remove the @ ๐Ÿ˜„

sullen shoal
#

keep in mind that TextChannel.mention exists if you're using Discord.py

drifting arrow
#

oh

#

psh dont need

#
channel = await createcategory.create_text_channel(f"Clan Create #{len(createcategory.channels)}", overwrites=overwrites)
        await interaction.response.send_message(f"{interaction.user.mention} - Please visit <#{channel.id}> to start and complete the clan create process.")
#

๐Ÿ˜„

slate swan
#

channel.metion

drifting arrow
#

It's fine.

#

both work

slate swan
#

but if you are wondering here are all formats

drifting arrow
#

Ty ty appreciate it.

sullen shoal
drifting arrow
sullen shoal
#

It is computationally slightly slower, that is an issue, for me

drifting arrow
#

How much slower?

slate swan
#

if there is a built-in method that does it why implement it yourself again

drifting arrow
#

Im not recreating it lol there's just 2 ways to get to the same destination

slate swan
#

if you are geting the same result it is recreating

sullen shoal
sullen shoal
# drifting arrow y u cross out

thinking about it now, I was wrong. However, Python is all about readability, and a word is more readable in this context than the raw syntax.

#

!e import this

unkempt canyonBOT
#

@sullen shoal :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | The Zen of Python, by Tim Peters
002 | 
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
011 | Although practicality beats purity.
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/mawelorina.txt?noredirect

drifting arrow
#

Neato

steady flume
#

someone knows what does it mean? this problem in db or in code (yesterday it was working)

whole shoal
#

Problem in db

#

Also don't host bot on replit ๐Ÿ’€

cold plover
#

hello

#

i need help about sth called hoodpay payment (if u knw )

steady flume
steady flume
whole shoal
steady flume
#

Iโ€™ve did it already ..

whole shoal
#

Try changing the db and running it and see if u get the same error

fading egret
#

whats the method to get the bots username in app_commands ?

slate swan
#

in where ?

#

do you have discord.Interaction ?

outer parcel
#

im tryiny to make an edit message check
It works but if i edit a previous message that was sent before the bot was turned on the bot just wont pick it up why is this?

uneven swan
#

Hi everyone, I got these problems with this code (its a discord bot) n idk why, I tried everything, can someone help me :/

slate swan
#

u have to move the things into the function

#

!indents

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

uneven swan
slate swan
slate swan
slate swan
lean girder
#

hi any one teach me python from scratch

#

@lean girder

fading egret
uneven swan
slate swan
slate swan
# fading egret yes

discord.Interaction has a .client attribute which is your bot, you can use .user attribute to get the user, and .name for the name of it

slate swan
slate swan
#

@uneven swan look into the chat on replit

uneven swan
#

i saw it

#

now i only have these 3 problems

slate swan
#

did you copy paste this code? @uneven swan

uneven swan
slate swan
#

so u want the command to be /say {text} and then the text should be sent? or wdym?

slate swan
#

upgrade to 3.7 or something imo

#

you mean you don't want the :
@slate swan used /say part ?

#

you should use interaction.channel.send

#

but note this

#

yh

#

not answering an interaction (like you are doing now with response.send_message) will make the command say this interaction didn't respond

#
await interaction.channel.send(...) # for users
await interaction.response.send_message("successfully sent text", ephemeral=True) # message only the user who used the command will see, used to remove the this interaction did not respond part
#

no not replace

slate swan
#

your welcome

fading egret
#

is there a way to group slash commands?

slate swan
#

You mean create sub commands?

fading egret
slate swan
uneven swan
#

i have this problem

vocal snow
#

what's the problem

uneven swan
vocal snow
#

you can always hover over it and see

#

or just run your code

#

in any case, it's because you're using await outside an async function

#

which is not allowed

uneven swan
#

the bot is online but, it doesn't show any rich presence

this the code ```activity = Activity(
name="Test",
type=ActivityType.playing,
state="Test",
details="Test",
emoji={"name": "๐Ÿฉ"}
)

await client.change_presence(activity=activity, status="online")```

slate swan
#

you can't await outside async functions

#

and you can't change presence before the bot has logged in

#

use the activity kwarg in the constructer

tender mantle
slate swan
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

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

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

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

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

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

New in version 2.0.
slate swan
#

!d discord.ext.commands.Bot.activity

unkempt canyonBOT
uneven swan
slate swan
#

what

uneven swan
tender mantle
steady flume
#

some knows this mistake with db and how to solve this ??

fading egret
slate swan
#

that won't work

#

slash group parents can't be invoked themselves

#

for example

#

if you have :
/parent and /parent child
then /parent won't be a valid command

#

!d discord.app_commands.Group

unkempt canyonBOT
#

class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., nsfw=..., auto_locale_strings=True, default_permissions=..., extras=...)```
A class that implements an application command group.

These are usually inherited rather than created manually.

Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only"), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds "discord.app_commands.guilds"), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions "discord.app_commands.default_permissions") will apply to the group if used on top of a subclass. For example:

```py
from discord import app_commands

@app_commands.guild_only()
class MyGroup(app_commands.Group):
    pass
```...
slate swan
#

use this

fading egret
rugged mountain
#
#m is a message object
            regexp = re.compile(r' ')
            match = re.split(regexp, m.content, maxsplit=2, flags=0)
            await bot.get_channel(int(match[0])).send(match[1])

if match[1] is a hyperlink, it's an empty string and won't send
I suspect this is because of embeds, but if match[1] is text and a hyperlink it works fine
even trying to escape the link with <> around it behaves similarly
what obvious thing am I missing here

rugged mountain
#

eh, nevermind
just made it check if the message has embeds and send it with or without embeds as necessary

outer parcel
#

how would i add options into my slash command

slate swan
#

you say that the choices will be strings but the values are booleans instead

#

change it to app_commands.Choice[bool]

gilded oxide
#
    @commands.has_permissions(manage_roles=True)
    async def create(self, ctx, user: discord.Member, *, role: discord.Role):```
#

im working on my role create command and idk how to finish it

uneven swan
#

somebody knows how to fix this

maiden fable
#

route*

#

not router

#

And stop using replit ๐Ÿ˜”

slate swan
#

@app_commands.checks.has_role(1017279032171188265)

how to make it work for 2 role ids (no need to have them both so u can use it but u need atleast one of them to use the commands)

uneven swan
uneven swan
maiden fable
slate swan
#

i only want 2 roles to use it

maiden fable
#

Ah, then use the has_role check twice

#

With different role IDs

slate swan
#

it didnt work

#

i tried already

maiden fable
#

Well then try adding an if statement to check if the person has both the roles

slate swan
#

i dont need him to have both roles i need him to have one atleast of them

cold sonnet
#

...

maiden fable
#

Bruh, you have has_any_role for that, if u want the command to work only for people which have at least 1 of the 2 roles

#

Hi Dani
Long time

slate swan
cold sonnet
#

Hi Hunter yes

maiden fable
slate swan
#

like
@app_commands.checks.has_role(1017279032171188265, id2)

#

oh ok i got u dw

maiden fable
cold sonnet
#

discord.py keeps getting more complicated yet the issues here keep getting numb

maiden fable
#

Lmao

cold sonnet
#

I mean not just telling people to learn the basics is a good thing but if people won't bother to learn python then this channel's gonna be flooded by dumb issues which aren't even related to the channel

#

most of the regulars are gone

maiden fable
#

True
I don't see any familiar faces here anymore, except sarth and Asher, that too once in a blue moon

cold sonnet
#

where's Ashley

#

I haven't mocked Ashley in ages

#

๐Ÿ˜”

maiden fable
#

He changed his name

cold sonnet
#

he

maiden fable
#

mhm

cold sonnet
#

I thought that was a joke

#

holy...

maiden fable
#

Yea.... Long story

slate swan
#

@shrewd apex would know

gilded oxide
#
    @commands.has_permissions(manage_roles=True)
    async def role(self, ctx, user: discord.Member, *, role: discord.Role):
        if role in user.roles:
            await user.remove_roles(role)
        else:
            await user.add_roles(role)

    @role.group()
    @commands.has_permissions(manage_roles=True)
    async def add(self, ctx, user: discord.Member, *, role: discord.Role):
        embed=discord.Embed(description=f"![add](https://cdn.discordapp.com/emojis/1097202934183383080.webp?size=128 "add") **{role} was added to {user}**")
        await user.add_roles(role,embed)

    @role.group()
    @commands.has_permissions(manage_roles=True)
    async def remove(self, ctx, user: discord.Member, *, role: discord.Role):
        embed=discord.Embed(description=f'![remove](https://cdn.discordapp.com/emojis/1097203033730977842.webp?size=128 "remove") **{role} was removed from {user}**')
        await user.remove_roles(role, embed)``` im trying to run these commands but idk what to use? like ,roleadd??
cold sonnet
#

no like ,role @summer canyon @role....

gilded oxide
#

ok

cold sonnet
#

oops wrong ping

#

damn it

#

but the role command is basically the same as the other two

#

you can use just
,add @gilded oxide role
or
,remove @gilded oxide role

gilded oxide
# cold sonnet you can use just ,add <@924820612545916948> role or ,remove <@924820612545916948...
    @commands.has_permissions(manage_roles=True)
    async def add(self, ctx, user: discord.Member, *, role: discord.Role):
        embed=discord.Embed(description=f":add: **{role} was added to {user}**")
        await ctx.send (embed=embed)
        await user.add_roles(role)

    @role.group()
    @commands.has_permissions(manage_roles=True)
    async def remove(self, ctx, user: discord.Member, *, role: discord.Role):
        embed=discord.Embed(description=f':remove: **{role} was removed from {user}**')
        await ctx.send(embed=embed)
        await user.remove_roles(role)``` I want the embed to send but it wont
cold sonnet
#

well it should

gilded oxide
#

idk why it won't

#

it adds the role and removes it

cold sonnet
#

the role command doesn't have this embed part

gilded oxide
#
    @commands.has_permissions(manage_roles=True)
    async def role(self, ctx, user: discord.Member, *, role: discord.Role):
        if role in user.roles:
            await user.remove_roles(role)
        else:
            await user.add_roles(role)

    @role.group()
    @commands.has_permissions(manage_roles=True)
    async def add(self, ctx, user: discord.Member, *, role: discord.Role):
        embed=discord.Embed(description=f"![add](https://cdn.discordapp.com/emojis/1097202934183383080.webp?size=128 "add") **{role} was added to {user}**")
        await ctx.send (embed=embed)
        await user.add_roles(role)

    @role.group()
    @commands.has_permissions(manage_roles=True)
    async def remove(self, ctx, user: discord.Member, *, role: discord.Role):
        embed=discord.Embed(description=f'![remove](https://cdn.discordapp.com/emojis/1097203033730977842.webp?size=128 "remove") **{role} was removed from {user}**')
        await ctx.send(embed=embed)
        await user.remove_roles(role)```
cold sonnet
#

did you use the role command or one of the other ones

gilded oxide
#

lemme try and see if the remove embed sends

#

the remove command doesn't work

cold sonnet
#

at all

#

do you get an error

gilded oxide
#

yea the role doesn't get removed

cold sonnet
#

this is a protocol I wanted to write while I was often here

#
  1. see if you get an error
  2. send the error if there is one,
    else check for an on_command_error or an on_error event which doesn't have an else: raise error
  3. end the event with else: raise error
  4. run the code again and send the error
#

there was definitely more to that

vocal snow
#

5: set up logging

#

Actually that should probably happen at the very very start

slate swan
#
import logging

logging.basicConfig(level=logging.INFO)
#

something like this should be good

slate swan
fading egret
#

i had the /test command i my bot earlyer
now i removed it from my code but its still showing up...
any1 knows how to remove it?

cold sonnet
#

sync

tender mantle
tired kernel
#

can somone help me on discord embeed

west escarp
#

probably, but people are very unlikely to say yes unless they know what specifically you need help with

#

It's the difference between "Can someone help me with a website" going between "Oh it just has to have my picture on it" and "the next facebook, you can do it for free right?"

tacit horizon
west escarp
#

Pillow can probably do that

tacit horizon
#

This website help ig

tender mantle
slate swan
#

why the hell this error is happening?

#

it's the first time it happens to me:

#
import bot_token
import discord
from discord.ext import commands
import os
import asyncio

client = commands.Bot(command_prefix='rpu->', intents=discord.Intents.all())


@client.event
async def on_ready():
    print("Sucess: Bot is connected to discord!")

async def load():
    for filename in os.listdir("./cogs"):
        if filename.endswith(".py"):
            await client.load_extension(f"cogs.{filename[:-3]}")

async def main():
    async with client:
        await load()
        await client.start(bot_token.return_token())

asyncio.run(main(), debug=False)
smoky sinew
#

that's not a problem with your code

#

you're trying to run your code in the python REPL

#

exit the python REPL using quit() before running your code

#

also you should use setup_hook to load your extensions

hushed galleon
#

yeah its kind of weird that the python plugin doesnt bother to check if it looks like a repl before attempting to run the file

slate swan
#

well, i just closed the terminal and now it's back working

smoky sinew
#

i don't use the run button in vscode

#

i open it in a separate terminal with my venv

outer parcel
#

How can i host my discord bot 24/7

junior falcon
#

Hi guys, i have a code that get some options from a yml file and creates an option for a dropdown menu with them it works fine but i dont know how to make a callback for every option. The callback should change the channel name and it is also specified in the configuration file.

This is my yaml file

dropdown:
#You can create as many options as you want, Max is 25 (Discord Limitation)
 option1:
  name: "Account"
  description: "For issues regarding your in-game account."
  emoji: ":bust_in_silhouette:"
  ticket_name: ":bust_in_silhouette:โ”ƒaccount-{interaction.user.name}"
 option2:
  name: "Store Support"
  description: "For issues regarding the store and payments."
  emoji: ":money_with_wings:"
  ticket_name: ":money_with_wings:โ”ƒstore-{interaction.user.name}"

This is how i get the values:

menu_options = [
        discord.SelectOption(label=dropdown[option_key]['name'], description=dropdown[option_key]['description'],
                             emoji=dropdown[option_key]['emoji'])
        for option_key in dropdown
    ]

And this is my dropdown:

@discord.ui.select(placeholder=ticketchannel['dropdown_placeholder'], min_values=1, max_values=1, options=menu_options,
                       custom_id=f"menu")
hushed galleon
junior falcon
tropic sable
#

how do i add a discord bot token in pycharm?

hushed galleon
# junior falcon There isn't a way to check if the selected values is equal to the first label na...

sure there is, it can very literally be written as you described py @discord.ui.select(...) async def my_select(self, interaction, select): for option in select.options: if select.values[0] == option.label: break though practically you might prefer discord.utils.get() instead: py option = discord.utils.get(select.options, label=select.values[0]) or even better, a dictionary mapping your option values to the corresponding entry in your config

hushed galleon
junior falcon
hushed galleon
# junior falcon Got it to work like that, thanks ```python for option_key in dropdown: ...

in your case i would prefer to set the option value to the corresponding yaml key and then use that for the lookup, its a bit nicer to write ```py
menu_options = [discord.SelectOption(label=option["name"], value=name) for name, option in dropdown.items()]

option = dropdown[select.values[0]]
await interaction.channel.edit(name=option["ticket_name"])``` editing channels also has a heavy ratelimit iirc so you might want to defer() beforehand

young dagger
#

How can I apply ratelimit for multiple functions?

tall temple
tropic sable
#

im very confused can someone explain what is happening

#

i copied this code from google i just wanna test discord bots first

tall temple
#

CTRL + R --> cmd --> pip install discord

slate swan
#

anyone knows how i can sync the tree commands to everyserver the Bot is on?

hushed galleon
hushed galleon
# tall temple huh ?

bot.slash_command() only exists in certain libraries and certain versions, e.g. pycord and nextcord

tall temple
#

oh i have to install pycord ?

hushed galleon
#

if you're using dpy 2.0 there's a different syntax for slash commands

tall temple
hushed galleon
#

domi you can iterate through client.guilds during that on_ready event and sync each one

slate swan
#

so like this?

hushed galleon
#

yup, though i would prefer to sync from a prefix command since on_ready can fire multiple times (depending on how frequently you restart your bot and connection stability), and syncing has a daily ratelimit

sick birch
#

Pretty sure if you leave out the guild argument tree.sync() syncs to all your guilds by default

junior falcon
#

Why bot.close() gives me this error? It works but throws this in console

Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000002860AE0C9D0>
Traceback (most recent call last):
  File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
    self._check_closed()
  File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000002860AE0C9D0>
Traceback (most recent call last):
  File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
  File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
  File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
  File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
RuntimeError: Event loop is closed
young dagger
#

Can you use while True and try in the same code as this?

while True:
    try:```
slate swan
#

yes but try need except block

#

!except

unkempt canyonBOT
#
Error handling

A key part of the Python philosophy is to ask for forgiveness, not permission. This means that it's okay to write code that may produce an error, as long as you specify how that error should be handled. Code written this way is readable and resilient.

try:
    number = int(user_input)
except ValueError:
    print("failed to convert user_input to a number. setting number to 0.")
    number = 0

You should always specify the exception type if it is possible to do so, and your try block should be as short as possible. Attempting to handle broad categories of unexpected exceptions can silently hide serious problems.

try:
    number = int(user_input)
    item = some_list[number]
except:
    print("An exception was raised, but we have no idea if it was a ValueError or an IndexError.")

For more information about exception handling, see the official Python docs, or watch Corey Schafer's video on exception handling.

outer parcel
#

How can I host bot 24/7 free

#

Like a small bot not much cpu or ram needed

swift acorn
#

I think that many cloud service providers have free tiers

#

that can support your bot

outer parcel
#

Where can I find them

#

The bot I want to host is quite small

swift acorn
#

Looks like google has a lot of results

outer parcel
#

Iโ€™ve been using replit but itโ€™s quite unreliable

swift acorn
#

but the big ones are AWS, Azure, or Google Cloud

outer parcel
swift acorn
#

The three I mentioned are the most trusted

outer parcel
#

Any tutorial on how to use them

swift acorn
#

There are plenty on youtube

outer parcel
#

Ty

young dagger
gusty flax
gilded oxide
#

how would I make these events for my antinuke
on member ban
on member remove
on guild update
on guild channel create
on role create
on role permission added

gusty flax
gilded oxide
full lily
#

like if you detect nukage remove the persons perms?

#

not sure what you mean by giving it attributes

gusty flax
smoky sinew
#

if you want a good way of making an anti-nuke, create a base Check class

#

and each Check can have its own events

gilded oxide
#

wtf is that.

smoky sinew
#

and then once a user failed too many checks ban them

gilded oxide
#

like make a class of checks?

smoky sinew
#

a base class and then extend it

#

that's how i would do it

slate swan
#

question. so when you're using super.__init__ in a view. if you have a function in the main class, do you need to set it as a parameter to run it in the view?

like for a randomizer. to repeat the function. would you want to use the randomizer in the __init__ or in the super.__init__for the view?

gilded oxide
gusty flax
smoky sinew
gusty flax
#

Unless ur gonna have a check class per event, which is a bit inefficient.

smoky sinew
#

this way you can set severity too

#

e.g. banning members is worth 3 points, adding a webhook is worth 1

#

10 points within 5 minutes = ban or something similar

young dagger
hushed galleon
#

essentially making an api wrapper like dpy, though it probably wont have to be anywhere as complex

slate swan
smoky sinew
#

e.g. ```py
class MyView(discord.ui.View):
def init(self, *, special_argument):
super().init()
self.variable = special_argument

slate swan
naive briar
#

You pass the arguments of the class you're inheriting in the super().__init__()

#

!e

class Base:
    def __init__(self, a):
        print(a)

class Sub(Base):
    def __init__(self, a, b):
        super().__init__(a)
        self.b = b

Base("uwu")
Sub("owo", "meow")
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | uwu
002 | owo
slate swan
gilded oxide
#

does someone know how to do data bases?

smoky sinew
gilded oxide
smoky sinew
#

uh ok

slate swan
vale wing
#

The Bases of Data

slate swan
#

can anybody tell me the meaning of os.system('cls')

near breach
#

Is there a documentation for the os module ?

vocal snow
#

!d os

unkempt canyonBOT
#
os

Source code: Lib/os.py

This module provides a portable way of using operating system dependent functionality. If you just want to read or write a file see open(), if you want to manipulate paths, see the os.path module, and if you want to read all the lines in all the files on the command line see the fileinput module. For creating temporary files and directories see the tempfile module, and for high-level file and directory handling see the shutil module.

Notes on the availability of these functions:

near breach
slate swan
#
    @commands.group(name="configure", invoke_without_command=True)
    @commands.has_permissions(administrator=True)
    async def configure(self, ctx, key:str, value:str):
        config_item = getattr(self.bot.config, key, default=None)
        value = value.strip()

        if not config_item or not value:
            await ctx.send("Config item or value not found")
            return

        item_type = type(config_item)
        if item_type == bool:
            if value.lower() == "true":
                setattr(self.bot.config, key, True)
                await ctx.send(f"{key} set to True")
            elif value.lower() == "false":
                setattr(self.bot.config, key, False)
                await ctx.send(f"{key} set to False")
            else:
                await ctx.send("Invalid entry ( True | False only)")
        elif item_type == int:
            if value.isdigit():
                setattr(self.bot.config, key, int(value))
                await ctx.send(f"{key} set to {value}")
            else:
                await ctx.send("Invalid entry ( Integer only )")
        elif item_type == str:
            setattr(self.bot.config, key, value)
            await ctx.send(f"{key} set to {value}")
        elif item_type == list:
            split = value.split(",")
            for i, val in enumerate(split):
                split[i] = val.strip()
            # If list provided
            if len(split) > 1:
                setattr(self.bot.config, key, split)
                await ctx.send(f'{key} set to {split.join(", ")}')
            else:
                if value in config_item:
                    config_item.remove(value)
                    await ctx.send(f'Removed {value} from {key}')
                else:
                    config_item.append(value)
                    await ctx.send(f'Added {value} set to {key}')
        else:
            await ctx.send("Unsupported config item type")
#

How bad of an idea is this

#

It's specifically for my server

#

I was too lazy to write commands for each config item so I instead write this which probably took about the same amount of time

#

But I mean... now any value can be set as I add it to the config without me having to add a "setter"

coarse knoll
#

A new Chapter! Happy spring everyone !!

proud gull
#

ะบะฐะบ ัƒั‡ะธั‚ัŒ python, ะณะพัะฟะพะดะฐ?

vale wing
# proud gull ะบะฐะบ ัƒั‡ะธั‚ัŒ python, ะณะพัะฟะพะดะฐ?

ะŸะพ ะฒะพะทะผะพะถะฝะพัั‚ะธ ั€ะตะบะพะผะตะฝะดัƒะตั‚ัั ะธัะฟะพะปัŒะทะพะฒะฐั‚ัŒ ะฐะฝะณะปะธะนัะบะธะน, ั‚ะฐะบ ะฑะพะปัŒัˆะต ะปัŽะดะตะน ัะผะพะณัƒั‚ ะฟะพะฝัั‚ัŒ ะธ ะฟะพะผะพั‡ัŒ

vale wing
jolly wave
#

print('Cookies -->', s.cookies.get_dict())
print()

#

what does this mean?

naive briar
#

Printing?

#

What's so confusing

slow fog
#

yeah printing

#

lol

worthy mantle
#

So what is the best framework that is feature rich and mostly future proof.
Also is discord.py dead?

slate swan
naive briar
#

What would you use received voice for anyway

slate swan
#

its useful in special cases but yeah not needed for most people

young dagger
#

So it won't reach the ratelimit

placid jolt
#

hi i have made a bot how would i give it multiple prefixes and how would i make a command with different names
same function different names
like status and stats for 1 command i dont wanna copy paste i feel like there could be a better way

hushed galleon
hushed galleon
hushed galleon
#

just based on their pip descriptions, ratelimit doesnt appear to support async/await

young dagger
# hushed galleon ratelimiting is a pretty common task that isnt related to discord development, t...

So is this how you would use it?

from limiter import AsyncLimiter

limiter = AsyncLimiter(max_calls=200, period=60)  # limit to 200 requests per 60 seconds

async def get_summoner_name(summoner_id, RIOT_API_KEY):
    url = f"https://euw1.api.riotgames.com/lol/summoner/v4/summoners/{summoner_id}"
    headers = {'X-Riot-Token': RIOT_API_KEY}
    async with limiter:  # acquire lock
        async with aiohttp.ClientSession(headers=headers) as session:
            async with session.get(url) as response:
                if response.status == 200:
                    json_data = await response.json()
                    return json_data["name"]
                else:
                    await asyncio.sleep(10)
                    continue

    limiter.release()  # release lock```
naive briar
#

Why are you calling .release()

#

They should be releasing it automatically after the async with block ends

young dagger
naive briar
#

Probably

hushed galleon
#

ah aiolimiter was what i was initially looking for but forgot the name of

tired kernel
#

how do i make a command wich deletes the trigger( for example i use ?help and then the bot deletes it)

drifting arrow
#

So currently if I want a new "Model" (The pop up input field)
I have to do this:

class ClanNameForm(discord.ui.Modal, title="Clan Name"):
    def __init__(self):
        super().__init__()
    ClanName = discord.ui.TextInput(
        label="Clan Name",
        placeholder=f"Your clan name here.",
        required=f"True",
    )

    async def on_submit(self, interaction: discord.Interaction):
        check_if_exists = await db.get_clan_by_name(clanname=self.ClanName.value)
        if check_if_exists:
            await interaction.response.send_message(f"The clan name: `{self.ClanName.value}` is already reserved or registered. Please submit a new one.", ephemeral=True)
            return
        await interaction.response.send_message(f"{self.ClanName.value} has been registered.", ephemeral=True)

Is it possible to do something similar to embeds? where it's like:

embed = discord.Embed()
embed.add_field()
#

Or would I need a new class for each form/modal?

hushed galleon
young dagger
# hushed galleon ah aiolimiter was what i was initially looking for but forgot the name of

So this would do it?

from aiolimiter import AsyncLimiter

rate_limit = AsyncLimiter(200, 60) # Limit to 200 requests per 60 seconds

async def get_summoner_name(summoner_id, RIOT_API_KEY):
    url = f"https://euw1.api.riotgames.com/lol/summoner/v4/summoners/{summoner_id}"
    headers = {'X-Riot-Token': RIOT_API_KEY}
    
    async with rate_limit: # use AsyncLimiter
        while True:
            async with aiohttp.ClientSession(headers=headers) as session:
                async with session.get(url) as response:
                    if response.status == 200:
                        json_data = await response.json()
                        return json_data["name"]
                    else:
                        await asyncio.sleep(10)
                        continue
tired kernel
# hushed galleon `ctx.message` refers to the message that triggered the command, so you'd call `....

@bot.command(aliases= ["Help"])
async def help(ctx,):
embed = discord.Embed(title="Need help for commands?", description= "List of all the commands:", color=discord.Color.blue())
embed.add_field(name= "Beta/beta", value="By using this command you will be putted in a review list to be part of the beta tester team.")
embed.add_field(name="Report/report", value= "This command is used for reports, Command structure= ?Report @user reason ")
await ctx.send(embed=embed, delete_after=30)
await ctx.message.delete()

Will this work?

hushed galleon
hushed galleon
drifting arrow
tired kernel
drifting arrow
tired kernel
hushed galleon
tired kernel
# drifting arrow ctx.author.mention?

so how do i add it

@bot.command(aliases= ["Help"])
async def help(ctx,):
embed = discord.Embed(title="Need help for commands?", description= "List of all the commands:", color=discord.Color.blue())
embed.add_field(name= "Beta/beta", value="By using this command you will be putted in a review list to be part of the beta tester team.")
embed.add_field(name="Report/report", value= "This command is used for reports, Command structure= ?Report @user reason ")
await ctx.message.delete()
await ctx.send(embed=embed, delete_after=30,)

young dagger
tired kernel
young dagger
# tired kernel it would help your ram

So this is my final code for it:

from aiolimiter import AsyncLimiter

rate_limit = AsyncLimiter(200, 60) # Limit to 200 requests per 60 seconds

async def get_summoner_name(summoner_id, RIOT_API_KEY):
    url = f"https://euw1.api.riotgames.com/lol/summoner/v4/summoners/{summoner_id}"
    headers = {'X-Riot-Token': RIOT_API_KEY}
    
    async with rate_limit: # use AsyncLimiter
        while True:
            async with aiohttp.ClientSession(headers=headers) as session:
                async with session.get(url) as response:
                    if response.status == 200:
                        json_data = await response.json()
                        await asyncio.sleep(0.3) # add 0.3 second delay
                        return json_data["name"]
                    else:
                        await asyncio.sleep(10)
                        continue```
tired kernel
#

however only a way to know

young dagger
#

I mean, if you guys know of any better way to do this, I'm open to hearing your proposition

fading egret
#

default_color = configData["DEFAULT_COLOR"]

TypeError: Expected discord.Colour, int, or None but received str instead.

is it possible to store the 0x56e2f5 inside the json otherwise?
or just convert it in the call, but in which type?

naive briar
#

Straight forward, isn't it

slate swan
#

it actually is int

#

!e print(type(0xffffff), 0xffffff)

unkempt canyonBOT
#

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

<class 'int'> 16777215
fading egret
vocal snow
#

Just cast it to int

#

It's a hexadecimal representation

#

!e ```py
print(int("0xffffff", 16))

#

What the

hushed galleon
#

dont forget the second argument

vocal snow
#

Oh yes

unkempt canyonBOT
#

@vocal snow :white_check_mark: Your 3.11 eval job has completed with return code 0.

16777215
vocal snow
#

Ty

hushed galleon
#

(even better would be using a file format that supports hex like toml/yaml)

fading egret
slate swan
#

!d discord.Colour.from_str *

unkempt canyonBOT
#

classmethod from_str(value)```
Constructs a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") from a string.

The following formats are accepted...
slate swan
#

this color preview thing is kinda nice ๐ŸคŒ

velvet compass
#

.color hex c0ffee

lament depotBOT
#
c0ffee

Color information for Hex c0ffee.

RGB

(192, 255, 238)

HSV

(164, 25, 100)

HSL

(164, 100, 88)

CMYK

(25, 0, 7, 0)

Hex

#C0FFEE

Name

No match found

velvet compass
drifting arrow
#

.color hex red

#

REE

fading egret
#

the script cannot find the module import yaml...

did the pip installed it in the wrong place?

vocal snow
fading egret
drifting arrow
drifting arrow
vocal snow
#

and you're right, pip installed it in the wrong place because pycharm creates a venv for each project

vocal snow
drifting arrow
#

Thus the reee

fading egret
velvet compass
drifting arrow
#

yes yes

fading egret
#

is there a way to get the bots avatar url in a slash command?

something like interaction.client.user.avatar_url ?

fading egret
slate swan
#

Also this will error if it has a default avatar

young dagger
shrewd apex
static holly
#

hi, how to code a percentage of chance?
exemple: "a" and "b"
if a=56%:
send message

#

please help me

slate swan
#

thats not discord bots related

#

you should ask in the proper place

golden portal
hazy vault
#

what's wrong

slate swan
#

the token is not a string

#

its None

hazy vault
slate swan
hazy vault
slate swan
# hazy vault

what is the point of puting the token to .env when you put it to getenv

#

!dotenv

unkempt canyonBOT
#
Using .env files in Python

.env (dotenv) files are a type of file commonly used for storing application secrets and variables, for example API tokens and URLs, although they may also be used for storing other configurable values. While they are commonly used for storing secrets, at a high level their purpose is to load environment variables into a program.

Dotenv files are especially suited for storing secrets as they are a key-value store in a file, which can be easily loaded in most programming languages and ignored by version control systems like Git with a single entry in a .gitignore file.

In python you can use dotenv files with the python-dotenv module from PyPI, which can be installed with pip install python-dotenv. To use dotenv files you'll first need a file called .env, with content such as the following:

TOKEN=a00418c85bff087b49f23923efe40aa5

Next, in your main Python file, you need to load the environment variables from the dotenv file you just created:

from dotenv import load_dotenv()

load_dotenv(".env")

The variables from the file have now been loaded into your programs environment, and you can access them using os.getenv() anywhere in your program, like this:

from os import getenv

my_token = getenv("TOKEN")

For further reading about tokens and secrets, please read this explanation.

velvet compass
#

Also, don't leak your bot token. Please reset it

hazy vault
#

thank

glad cradle
slate swan
#

Because people can get full access to your bot and do anything with it

glad cradle
#

i was sarcastic

cold sonnet
#

I make exactly that face when being sarcastic

glad cradle
#

you're my second account

slate swan
cold sonnet
#

cool

maiden fable
#

Nice

sick birch
#

epic

slate swan
#

awesome

glad cradle
#

unbeliavable

slate swan
#

sheesh

slate swan
#

Anyone has a idea what kind of bot i could make?

sick birch
#

The possibilities are endless :3

slate swan
#

ik but i dont know what i should do tbh

sick birch
unkempt canyonBOT
#
Kindling Projects

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

sick birch
#

You could incorporate any of those into a discord bot without too much effort

slate swan
#

Thanks!

young dagger
#

What is the most efficient way to run tasks every third day?

young dagger
#

I have a feeling that "@tasks.loop(hours=72) " is giving me "Can't keep up, shard ID None websocket is 37.4s behind."

#

I don't know what else it could be

sick birch
young dagger
sick birch
#

No

#

The blocking function could be anywhere in your code

#

Not strictly restricted to the task itself

young dagger
#

Would you review my code and help me out? Because I cannot find it ๐Ÿ˜ฆ

young dagger
#

No

#

Aiohttp everytime

glad cradle
#

iirc there were some asyncio things that you could setup to debug your code

sick birch
young dagger
sick birch
#

I prefer if it was kept here if possible

young dagger
#

I don't feel like sharing my entire bot to the public

young dagger
sick birch
#

Alright, that's fine

#

@young dagger looks fine for the most part - might be the usage of Pymongo?

#

It's also wholly possible either your host machines network fell behind or Discord fell behind or anything in between so it may not even be with your code

tropic sable
#

anyone know how to fix this

young dagger
slate swan
tropic sable
slate swan
#

dont name your file discord.py as its the module name

tropic sable
timid spade
#

how can i know if user have boosted the server one time only or multiple times

young dagger
# sick birch

I think that is just for the "ReturnDocument.AFTER" since motor doesn't have that.

counter_doc = await counter_collection.find_one_and_update({"_id": "case_counter"}, {"$inc": {"count": 1}},
                                                                           return_document=ReturnDocument.AFTER)```
tropic sable
#

i fixed it ty

#

how do i make the bot active btw

#

๐Ÿ˜ญ sorry im kinda new to this

#

sorry i dont get you

#

i legit started yestarday and thought i would try testing with bots im rusing things huh ๐Ÿ˜ญ

turbid condor
#

Where token= bot token u get it from dev portal

tall temple
#

everyone

tropic sable
#

okk ty

tall temple
#

can someone help about something ?

#

a simple thing for you i guess

turbid condor
#

But that's the simplest way i know of explaining after u already told them about run function

tall temple
#

something like this, py ctx.server.id = ctx.server.id with open(f'users_data\{ctx.server.id}.json', "w") as users_data : json.dump(test, users_data)
i want to attribute to the file name the guild id where the command will be executed

#

discord module you mean hihi ?

#

oh ok

#

๐Ÿ˜น yeah i'm using it

turbid condor
#

Yeah discord uses guild to describe server

tall temple
turbid condor
#

Tho don't know why

#

It's their documentation

tall temple
#

๐Ÿ˜น

#

but i want to arribute to my file name a value that i don't know :/

#

idk how to process

turbid condor
#

I guess so

tall temple
#

oh ok

#

wym ? huh

#

sorry i'm a python beginner

#

@slate swan hm ?

slate swan
#

No, using x will raise an error if the file already exists

tall temple
#

but it's not what i'm searching for

#

explain pls huh

slate swan
#

Maybe they want to replace it if it already exists ?

tall temple
#

@slate swan could you help me in dms ?

#

to get more reactive answers

ornate crater
timid spade
#

anyone have a sample code for discord.ui.Button use?

ornate crater
#

wait

tall temple
#

btw, are you french ?

#

๐Ÿ’€

young dagger
tall temple
#

passe dm, jsuis plus ร  l'aise en francais pour t'expliquer mon soucis :D

thin raft
#

any ideas on hwo could I host my bot and the bot's website at the same time?

#

I was thinking of having 2 python instances but idk if that's ok

slate swan
#

Yeah you shouldn't run them in one terminal

#

Use one for bot and another for site

#

They can communicate with ipc

thin raft
magic whale
#

hello

#
@code_bot.tree.command()
async def test(interaction: discord.Interaction):
    await interaction.response.send_message("Hello")
    await interaction.response.edit_message(content="Hello edited")

i am trying to edit the message i send as response to user but it is giving me error

#

can someone tell me what i am doing wrong?

thin raft
#

!d discord

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

magic whale
#

this one. i have been trying to solve it but couldn't solve it

thin raft
#

discord.Interaction.followup

#

discord.Interaction.followup returns a webhook

#

which you can edit via

hushed galleon
#

id recommend edit_original_response instead, but i wonder if that method actually works with an interaction webhook

hushed galleon
#

!d discord.Interaction.edit_original_response

unkempt canyonBOT
#

await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the original interaction response message.

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

This method is also the only way to edit the original message if the message sent was ephemeral.
hushed galleon
#

how so

thin raft
#

!d discord.Interaction.message

unkempt canyonBOT
thin raft
#

try what I said first @magic whale

#

he wanted to edit

magic whale
#

it says webhook object is not callable

thin raft
hushed galleon
magic whale
#

Command 'test' raised an exception: TypeError: 'Webhook' object is not callable

hushed galleon
thin raft
#

I mean

magic whale
#

this is replying to the message

thin raft
#

isn't the response a message?

magic whale
#

not editing it

thin raft
#

or it doesn't count as one because it is an app command

unkempt canyonBOT
#

await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the original interaction response message.

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

This method is also the only way to edit the original message if the message sent was ephemeral.
hushed galleon
thin raft
#

makes sense then

thin raft
#

yo what

#

when did they change the ui?

hushed galleon
#

has it changed?

magic whale
#

what do i do now?

thin raft
#

but it has

hushed galleon
magic whale
hushed galleon
#

what library are you using?

magic whale
hushed galleon
#

and version?

magic whale
#

latest

thin raft
#

which one is latest now im wondering

hushed galleon
#

what does latest mean, like the last time you used pip install git+https://github.com/Rapptz/discord.py?

thin raft
#

!d discord

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

thin raft
thin raft
#

2.2.2

hushed galleon
magic whale