#discord-bots

1 messages · Page 171 of 1

flint bolt
#

thats what i do

#

how do i put that in?

viral stump
#
            await start_a_tour()
            await message.channel.send(f"{sleep_amount} saniye içerisinde geldim.")
        except:
            await message.channel.send(f"Oda boş olduğundan ya da hedef oda da olmadığından dolayı bot gelmiyor. Hedefler aşşağıda")
            for victim_user_id, percentage in targeted_victims:
                idlist = await bot.fetch_user(victim_user_id)
                chance = (percentage * 100)
                await message.channel.send(f"{idlist.display_name} ve %{chance:.0f}")```
naive briar
#

What

viral stump
#

okay i will write cleaner

naive briar
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

viral stump
#

Right now, output is like

Target#xxxx and chance was %xx
Target2#xxxx and chance was %xy

i want like

Target2#xxxx and chance was %xy```
naive briar
#

Output where

viral stump
#

except one is output

naive briar
#

Also add py after the first triple backticks to highlight the syntax

naive briar
viral stump
#

its doing like that

#

wait a sec

viral stump
#

i want one line, not two line

naive briar
#

Join them together

viral stump
#

i didnt get it

#

what you mean

naive briar
#

I

#

I hate formatting

#

!e

ml = []

for a in (0, 1, 2):
    ml.append(f"Int({a})")

print("{}\n{}\n{}".format("'''", "\n".join(ml), "'''"))
unkempt canyonBOT
#

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

001 | '''
002 | Int(0)
003 | Int(1)
004 | Int(2)
005 | '''
naive briar
#

Just change the quotes to backticks

#

!d str.join

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.
flint bolt
naive briar
#

You should use aiosqlite btw

#

Or just any asynchronous SQLite package

somber imp
#

aiosqlite > asqlite

viral stump
#

py except: await message.channel.send(f"Oda boş olduğundan ya da hedef oda da olmadığından dolayı bot gelmiyor. Hedefler aşşağıda") for victim_user_id, percentage in targeted_victims: idlist = await bot.fetch_user(victim_user_id) list = "" list += (f"{idlist.display_name} ve %{chance:.0f}") chance = (percentage * 100) await message.channel.send(f"3xbacktick{list}3xbacktick")
UnboundLocalError: local variable 'chance' referenced before assignment

#

3xbacktick = ```

naive briar
#

Put py before the backticks to highlight the syntax so it's more readable

somber imp
#

thats not how you use fstrings

#

or 3xbacktick is not a variable

naive briar
#

Also you're creating new string for every iteration

#

This variable won't exist in the first iteration

somber imp
viral stump
#

no, there is no 3xbacktick on code, i wrote it because discord really fucks it up and i dont know how to fix it

somber imp
#

ah ok i thought so

viral stump
naive briar
#

You're still creating new list variable in every iteration

#

Also don't override built-in functions

somber imp
somber imp
#

name it something like percent_list or smth

viral stump
#

okay, i swapped

#

and it worked but not exactly

#

it worked for 1 time, not for loop

#

it wrote only one loop

naive briar
viral stump
#

oh fuck i didnt see it

#

output: Dyno ve %50ValoMarket Bot ve %50

#

okay it works but new line not works

somber imp
#

you didnt put a new line

viral stump
#

because of course i didnt add it

naive briar
#

You're not adding new line

somber imp
viral stump
#

okay, i added ...0f}\n") and seems like it works

#

Thank you guys @somber imp@naive briar

somber imp
#

np 🙃

spring parcel
#

Hi

slate swan
#

whats wrong with Intents ?

naive briar
#

You need to create an instance of it

#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, 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

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

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

slate swan
#

still the error

#

ahh i had intents=Intents

naive briar
slate swan
#

yes fixed

#

and do u know why i cant see my /nc command ?

naive briar
#

It's prefix command

slate swan
#

no slash command ?

#

ah u are right

#

its a prefix command

#

but why its not a slash cpmmand.?

#

im using pycord

#

hello

#

which rdp do yall reecommend

naive briar
#

What's rdp

slate swan
slate swan
gusty bobcat
#

I have a question

naive briar
#

Just ask it

naive briar
slate swan
#

10 a month for projects just not it

gusty bobcat
slate swan
#

ofc

#

i dont see my nc cmd

#

You didn't register as slash command

#

what u mean

#

Are you using pycord

#

ye

#

@bot.slash_command(name="nc")

#

remove @bot.command

slate swan
#

cant send embed in a slash command ?

#

@slate swan

#

Switch line 19 and 20

#

embed=discord.Embed(...
embed.set_author...

slate swan
bright wedge
slate swan
naive briar
#

Pycord

slate swan
slate swan
#
Traceback (most recent call last):
  File "main.py", line 23, in <module>
    client.run(tkn)
  File "/home/runner/carbon/venv/lib/python3.8/site-packages/discord/client.py", line 828, in run
    asyncio.run(runner())
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/home/runner/carbon/venv/lib/python3.8/site-packages/discord/client.py", line 817, in runner
    await self.start(token, reconnect=reconnect)
  File "/home/runner/carbon/venv/lib/python3.8/site-packages/discord/client.py", line 746, in start
    await self.connect(reconnect=reconnect)
  File "/home/runner/carbon/venv/lib/python3.8/site-packages/discord/client.py", line 672, in connect
    raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.```
#

how to fix this

pulsar kettle
#

Hello, I'm trying to add a timeout/untimeout feature to my Discord.py bot but I can't figure out how to do it. I've tried looking on YouTube but they either don't work or only work with custom commands prefixes when I need slash commands. Can anyone help out please? (Beginner to coding, so dumb it down for me please <3)

naive briar
naive briar
pulsar kettle
slate swan
#

Hello

#

unknown interaction
why is this error showed up ?

somber imp
#

You took more than 3 seconds to respond

#

Defer the Interaction at the beginning of the callback and send followup instead of response where you want to

slate swan
supple ridge
#

any idea how can i split this embed so it gives me percentage?

loud junco
#

how do u want it to split

#

u only wants the percentage?

supple ridge
#

yea

loud junco
supple ridge
loud junco
#

try to get the message first

#

after that do some message filter

cerulean elbow
#

Hi I'm trying to make premium bot commands (for members with the premium role in my server). But its not storing the info in premium_users.json. Using d.py Help needed pls thanks

cerulean lichen
#

nope, created it twice

supple ridge
loud junco
supple ridge
loud junco
supple ridge
#

that's why i came here

upbeat otter
#

not like I know how it works

#

you could achieve the same without regex too

#

But messy

rustic edge
#

Hello!

Is it possible to restart the bot within istelf without killing the script? I want to use this feature because I'm running my bot on a Unix server and my problem is when I use a service such as nohup to keep it running, I'm not able to kill it when I pull new changes from GitHub. How would I go about doing this?

vale wing
#

Updating the bot without killing the script is done through reloading extensions

#

I would recommend using docker instead of nohup

#

That's completely different thing tho

rustic edge
#

ooh i hadnt thought of that

#

ty

naive briar
unkempt canyonBOT
#

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

['50.0%', '49.0%']
vale wing
#

Better \d+(?:\.\d+)% imo

quick gust
#

uve just spoon fed him

vale wing
#

Who

quick gust
#

catgal

naive briar
#

What else are you gonna do 🤷

vale wing
#

Catgal isn't one who needs spoonfeeding

shrewd apex
quick gust
#

no, catgal has just spoonfed the other guy

vale wing
quick gust
vale wing
#

Rate link regex https?://[-\w]+\.\w{2,4}(?:/[-\w%&?=#@]+)*

vale wing
shrewd apex
#

!e

import re
pattern = r'\d+\.?\d*%'
string = """0000 :emoji: • Lvl. 1 • 50.0%
0001 :emoji: • Lvl. 5 • 49.0%"""

print(re.findall(pattern, string))
unkempt canyonBOT
#

@shrewd apex :white_check_mark: Your 3.11 eval job has completed with return code 0.

['50.0%', '49.0%']
shrewd apex
#

😎

naive briar
#

🐁

cold sonnet
#

did someone say meh

vale wing
#

I said bobuz

shrewd apex
vale wing
#

Ash vs Asher 🥶 battle

cold sonnet
#

who's the real one

upbeat otter
#

none

cold sonnet
#

thought so

vale wing
#

Asher has an advantage of being bobux developer

#

Idk how that's an advantage but anyway

shrewd apex
#

net worth is higher

vale wing
#

Ah yes

cold sonnet
#

I'm gonna have a dog like this

shrewd apex
#

nice

vale wing
#

Nice dog

#

But can it bring bobux

shrewd apex
#

u all still have aspirations 😔

upbeat otter
cold sonnet
#

you did not just say that

#

you can see I'm a crocodile

cold sonnet
#

crocolate

quick gust
#

also !ot

cold sonnet
vale wing
#

Discord bots is for everything

upbeat otter
#

^

vale wing
#

Like when you say "I am going to get this dog" you actually mean "how can I make a discord bot that can give me a dog based on my calculations"

cold sonnet
#

!dog

unkempt canyonBOT
#
Did you mean ...

» dotenv
» docstring

quick gust
#

💀

cold sonnet
#

shut up bot

vale wing
#

!pypi exenenv

unkempt canyonBOT
quick gust
#

Dogstring

vale wing
#

Almost same

upbeat otter
#

dog

#

!pypi dog

unkempt canyonBOT
#

dog is a simple wrapper for "docker run" to make it simple to call tools residing inside docker containers

upbeat otter
#

😳

vale wing
#

Lol wtf

upbeat otter
#

how does dog relate to docker lmao

cold sonnet
#

how does it make docker simple

#

I'm mad at this lib for taking the name 'dog' so unnecessarily

vale wing
#

By barking

upbeat otter
#

😔 you're too much of a person who "thinks out of the box"

vale wing
#

I am spying on infernum

cold sonnet
#

huge server

maiden fable
#

Dayumn

quick gust
quick gust
#

but like wtf is this bot, im so confused

vale wing
#

I haet disney internals 😡🤬😤

        # noinspection PyProtectedMember 
         interaction._state._modal_store.remove_modal(interaction.author.id, interaction.custom_id)```
vale wing
quick gust
#

which manual

cold sonnet
#

I don't understand anything from that

vale wing
#

You earn bobux by doing stuff

#

That's the manual

shrewd apex
vale wing
#

You mean what

quick gust
#

what's the use of bobux if i may ask

vale wing
#

I use exponential growth

vale wing
shrewd apex
vale wing
#

You can join development server we share news there but you will be able to spend it

vale wing
quick gust
vale wing
#

People see bot, they want to add it to their server

#

The more servers the more people

#

And the bigger servers

#

We can actually count how many users bobux serves rn

#

140k

#

Not that much but something

quick gust
#

one fourty thousand?

maiden fable
#

Lmao

vale wing
#

Um actually 1000 1000 1011 1000 00

quick gust
#

the hell

upbeat otter
quick gust
#

💀

maiden fable
#

Nice

upbeat otter
#

Hunnie Bunnie

#

Hi

vale wing
#

Wait it didn't update?

#

That's outdated description

maiden fable
#

Lmao

vale wing
#

That's old version

upbeat otter
#

idk

#

lemme

#

same thing

maiden fable
#

I think u all will want to move this to an ot

vale wing
#

Um actually, according to my calculations, we are currently talking about a discord bot

#

🤓

maiden fable
#

Not discord bot development

upbeat otter
#

It's about a discord bot

#

let's start criticizing bobux bot then 😳

maiden fable
#

Still not the convo about discord bot development

vale wing
#

Ok

upbeat otter
vale wing
#

Guys what's best implementation for settings

maiden fable
#

Smh

vale wing
vale wing
upbeat otter
maiden fable
#

Wait, bobux is your bot?

vale wing
#

Yeah I am project manager and there are 4 other devs in team

shrewd apex
#

legendary team

vale wing
#

It's closed source tho

maiden fable
#

Am I the only one who thought it was some random bot giving free currency lmao

upbeat otter
vale wing
#

Idk

upbeat otter
shrewd apex
shrewd apex
upbeat otter
#

lmao

maiden fable
#

But good work, having 140k users, Evenifix!

vale wing
#

We will probably invite someone else if one of current devs leaves or when we will be developing site

shrewd apex
#

js

maiden fable
#

For my bot, its hardly 9.2k 😭

vale wing
#

Screw js

#

Django is my girlfriend

torn sail
maiden fable
#

Eh, but my bot is hardly used lmao

upbeat otter
shrewd apex
#

nice i am trying to get my bot in more servers rn 😅

#

failing miserably

upbeat otter
shrewd apex
#

🔥

shrewd apex
upbeat otter
#

sad

maiden fable
upbeat otter
#

I'll add it to my server 😔

#

ChatGPT moment

maiden fable
#

.......?

upbeat otter
#

...

vale wing
maiden fable
#

I don't have one
I got a first floor tho

cold sonnet
lapis light
#

yooooo guys
What's mean of ```py
'NoneType' object has no attribute 'id

maiden fable
#

That means your object is None

paper sluice
unkempt canyonBOT
#

@paper sluice :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | AttributeError: 'NoneType' object has no attribute 'id'
maiden fable
#

your get method is returning None, meaning the ID is wrong or u r passing a string instead of int

lapis light
#

aha

maiden fable
#

Can u show the whole traceback?

lapis light
#

sure!

#
Traceback (most recent call last):
  File "C:\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'createyoutuberchannel' raised an exception: AttributeError: 'NoneType' object has no attribute 'id'
maiden fable
#

Is that it?

#

weird

#

Hey also

#

Use interaction.guild.get_role

paper sluice
#

what is get??

maiden fable
#

discord.utils.get

#

from discord.utils import get

lapis light
paper sluice
#

oh 👀

lapis light
#

but not working for member id

maiden fable
#

wym

lapis light
#

get is working for role

#

there is a problem

maiden fable
#

Tbh the only thing u can do is print all the objects and see if something is returning/printing None

lapis light
#

and my problem is when i use youtuber_id as arg for using it in slash command , it won't find that

upbeat otter
shrewd apex
#

whats wrong with using a laptop 🗿

potent spear
#

not everyone has access to that I guess, I've seen way to many people even code on mobile, that's dedication

vale wing
#

Sell phone buy laptop

shrewd apex
vale wing
#

Well if he's addicted to apple, laptop can only mean "mac book pro max 69 ultra"

#

And it def costs more than ipad

potent spear
potent spear
vale wing
#

Actually normal laptop is around 700$ ig

potent spear
#

give the man a nice chromebook

shrewd apex
vale wing
#

Um mom I need RTX 4090 for my studies

shrewd apex
#

u can get a decent model as well

supple ridge
upbeat otter
supple ridge
#

sleep sleep

upbeat otter
vale wing
#

Mom wouldn't probably see the difference between 4090 and 3070

upbeat otter
#

what isn't a list
idtts your question's even related to this channel

vale wing
#

.split() returns a list, not replaces the string with list

#

!e py s = "stuff, vodka, free bobux" words = s.split(", ") print(words)

unkempt canyonBOT
#

@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.

['stuff', 'vodka', 'free bobux']
rare echo
#

free bobux you say?

vale wing
#

Yus

torn flame
#
B = 2
c = 3

def d():
    c = c + a
    
d()

print(c)```
#

why is thiis not working

vale wing
#

How is this related to discord bots

torn flame
#

i use this in my bot

rare echo
torn flame
#

im sorry where should i ask for help?

rare echo
vale wing
#

I use a RandomForestClassifier machine learning model in my code, it's definitely more of discord bot than AI

#

🤓

slate swan
lean palm
#

!e

a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
print(a[0:10:4])
print(a[::4])
unkempt canyonBOT
#

@lean palm :white_check_mark: Your 3.10 eval job has completed with return code 0.

001 | [1, 5, 9]
002 | [1, 5, 9, 13, 17]
slate swan
#

do u know how to get the inviter?

jade lodge
#
@client.command()
async def test(msg):
    embed=discord.Embed(title='Hello', description='This is a Embed', color=0x1936275)
    await msg.channel.send(embed=embed)```
#

Why it is not sensing me response prefix is !
I writing
!test it not giving me response

sick birch
slate swan
#

!d discord.Intents

unkempt canyonBOT
#

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

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

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

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

New in version 1.5.
jade lodge
#
client = commands.Bot(command_prefix ='!', intents=discord.Intents.all())

sick birch
#

I would not recommend undertaking an invite system unless you can work at a high level

jade lodge
#

@slate swan

sick birch
#

(And follow imperative instructions)

jade lodge
#

I can't understand

#

@sick birch

sick birch
slate swan
#

Do you have an on_message event eating up the messages

jade lodge
#

Wait

#

@slate swan

slate swan
#

So on_message is called whenever the bot sees a message being sent, which by default calls await Bot.process_commands(), which basically tells the bot to treat the message as a command. You've overwritten this event but not called the process_commands method.

slate swan
#

Oh and also, the hex digit passed as your embed colour is 7 digits when it must be a 6-digit hex number @jade lodge

sick birch
# slate swan wdym

Am invite system. Discord doesn't just tell you who a new member was invited by. You need to cache the total invites for each server in memory, and do a differential lookup for each new on member. Update the cache again

slate swan
#

Also why bro is coding in the 1800s

jade lodge
#

@slate swan pydroid 3

#
@client.event
async def on_message(msg):
     if msg.content == "!embed":
        embed=discord.Embed(title='Hello', description='Hello mannn')
        msg.channel.send(embed)```
#

@slate swan

slate swan
#

inconsistent use of tabs & space

jade lodge
#

Im new

slate swan
#

it's not related to discord.py but related to python

#

welp just delete all the spaces that you've in indentation of that function & replace 'em with either space or tab

jade lodge
#

@slate swan

#

@slate swan

slate swan
#

man

#

just fix your indentation 🙂

jade lodge
#

What is it

upbeat otter
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

jade lodge
#

@upbeat otter

#

@slate swan

upbeat otter
#

YES

#

stop pinging people, that's rude

jade lodge
#
@client.event
async def on_message(msg):
    print(colored(msg.channel.id,color="green"),"kanalındaki",colored(msg.author,color="red"),"`in mesajı:\n",colored(msg.content,color="cyan"))
    if msg.content == "!embed":
        embed=discord.Embed(title='Hello', description='Hello mannn')
        await msg.channel.send(embed)```
upbeat otter
jade lodge
#

Now i trying it haha

upbeat otter
#

"haha"

primal token
slate swan
upbeat otter
primal token
#

🤨

slate swan
#
TypeError: Embed.set_image() takes 1 positional argument but 2 were given```
#

@sick birch

primal token
#

!d discord.Embed.set_image

unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.
slate swan
slate swan
#
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\user\Desktop\Other\Bots_For_Sell\Hesham hope bot\bot.py", line 37, in join_callback
    await clickj.response.defer()
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 592, in defer
    await adapter.create_interaction_response(
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
#

@primal token can u help ?

solid orbit
#

hi, i am learning python and the first thing i want to do with it is to create a discord bot. Do you know ways to learn making discord bots? because youtube videos and most courses are not really good code

fading marlin
sick birch
solid orbit
#

because it seems really fun to make discord bots to me

#

!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
vale wing
sick birch
amber folio
#

Hey guys, does anyone know if there’s any way to actually pull user/member connections through commands? I know that bots aren’t able to access that info. But if you give your application the “connections” parameters in your OAuth2, how can that be utilized?

slate swan
potent light
#

What's the function to stop the function from running until voice_clients.play() finishes?

slate swan
#

can someone hep me ot says ‘bot’ onject has no attribute ‘slash_command’

torn sail
slate swan
#

@polar wigeon hey you know python right? i need some help

slate swan
#

@slate swan

#

<>

#

&

polar wigeon
#

<&

slate swan
#

@slate swan

mental hollow
#

my code should send a webhook when a user changes their avatar, which is does, however their avatar before the change for whatever reason is not displayed.. I noticed this & tested it myself, my avatar before & after both display
Here’s my code:

if before.display_avatar.url != after.display_avatar.url:
                        e = discord.Embed(colour = 0x2f3136)
                        e.set_author(name = f"{before.name} changed their avatar!", icon_url = self.bot.user.display_avatar.url)
                        e.description = "The images will be provided below."
                        e.set_footer(text = "This event occured:")
                        e.timestamp = discord.utils.utcnow()
                        e1 = discord.Embed(colour = 0x2f3136)
                        e1.set_author(name = f"This is {before.name}'s avatar before:")
                        e1.set_image(url = before.display_avatar.url)
                        e2 = discord.Embed(colour = 0x2f3136)
                        e2.set_author(name = f"This is {before.name}'s avatar after:")
                        e2.set_image(url = after.display_avatar.url)
                        await logWeb.send(embeds = [e, e1, e2])

Here’s some attachments:

#

please ping me if anyone responds :)

slate swan
mental hollow
#

^ I’m gonna try fetch the user

slate swan
#

and the bot can't interact with it lol

mental hollow
#

ah

mental hollow
slate swan
#

not that im aware of

slate swan
#

works in right instance but not the left been fucking with it for hours

naive briar
#

What

slate swan
#

the cmd_clan_accept and cmd_clan_create

fading marlin
#

what about it? I just see some red squiggly lines in async

slate swan
#

YEA NO SHIT i need it fixed lmfao

#

😭

#

i sad man i need my bot to work 😡

fading marlin
#

well we've got no clue what's wrong lol

#

you haven't showed us any errors either

pulsar bridge
#

Is there a way to use checks with slash commands?
Been looking around and haven't found much..
Just need to check if a user has one role out of a few when their running the command, and it won't run if they don't.
And then having a sepreate check under that, which will also allow them to run the command if they have the Admin or Manage Guild perms.
The bot command version would be:

@bot.command(name='yy')
@commands.check_any(commands.is_owner(), is_guild_owner(), commands.has_role("x"), commands.has_role("y"), commands.has_role("x"))
@commands.check_any(commands.has_permissions(administrator=True), commands.has_permissions(manage_guild=True))
async def xx(ctx):
 '''Code'''
sick birch
naive briar
#

!d discord.app_commands.check

unkempt canyonBOT
#

@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.

These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure") exception is raised and sent to the appropriate error handlers.

These checks can be either a coroutine or not.

Examples

Creating a basic check to see if the command invoker is you...
sick birch
#

!d discord.app_commands.checks.has_role

unkempt canyonBOT
#

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

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

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

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

New in version 2.0...
sick birch
#

There's also this

pulsar bridge
slate swan
#

how does one setup a command that will make a cache of the data?
i wanna make a role react command for my discord and a friends that will be something like yagpdb
!addrolereact message.id role.id emoji

rare echo
naive briar
#

If you're making react roles, you should use a database 🍬

slate swan
#

i saw sqlite and peewee as the main ones people have made content and using it as their db.

naive briar
#

If your bot is private or still smol, SQLite3 is enough

#

!pypi aiosqlite

unkempt canyonBOT
slate swan
#

ty!

slate swan
fast musk
#

Postgres

upbeat otter
#

Just use postgres since it'll be easier later

slate swan
#

json wen

upbeat otter
#

no db when

slate swan
#

json is not a db

upbeat otter
#

bro

slate swan
#

is there an easier way to read the discordpy.readthedocs.io? cause honestly, this is annoying not having a list of all possible events/listeners...etc

unkempt canyonBOT
#

Hey @pulsar bridge!

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

pulsar bridge
#

Ran into this error when trying to start my bot. (Error -> https://paste.pythondiscord.com/ahuqutukef)
I'm using only application commands.
Line 46 is:

load_dotenv();
PERSONAL_GUILD_ID = os.getenv('PERSONAL_GUILD_ID')
PERSONAL_GUILD = discord.Object(id=PERSONAL_GUILD_ID)

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

    async def setup_hook(self):
        self.tree.copy_global_to(guild=PERSONAL_GUILD)
        await self.tree.sync(guild=PERSONAL_GUILD)  # <- Line 46

client = TheClient(intents = intents)

Maybe I've invited the client wrong?
I'm used to using a bot, and bot commands, but now I'm using interactions / slash commands.
Is there a different way I should be inviting it?

proud tiger
#

!else

unkempt canyonBOT
#

for-else

In Python it's possible to attach an else clause to a for loop. The code under the else block will be run when the iterable is exhausted (there are no more items to iterate over). Code within the else block will not run if the loop is broken out using break.

Here's an example of its usage:

numbers = [1, 3, 5, 7, 9, 11]

for number in numbers:
    if number % 2 == 0:
        print(f"Found an even number: {number}")
        break
    print(f"{number} is odd.")
else:
    print("All numbers are odd. How odd.")

Try running this example but with an even number in the list, see how the output changes as you do so.

upbeat otter
#

use #bot-commands , this is for discord bot development not using the server bots

cold sonnet
#

cool

pulsar bridge
upbeat otter
#

and whatever's around it

#

just a bit

pulsar bridge
# upbeat otter Show the `cmdtas` whatevrr funtion
    '''Code'''
    await interaction.response.send_message(embed=embed)

@client.tree.command(name='view_command')
@app_commands.checks.has_any_role("Mod", "Moderator", "Discord Staff", 'Community Assistant')
#@app_commands.checks.has_permissions((administrator==True))
@app_commands.describe(
    ID='The ID of the command you want to see details of.'
)
async def cmd_dtas(interaction: discord.Interaction, ID: int = None):
    proceed = 2
''' Code '''
upbeat otter
pulsar bridge
#

Kk

upbeat otter
#

welcome

slate swan
#

so if ur on... discord.on_ready()... you can't put anything in the ()? so then how does it call members, guild info, etc?

naive briar
#

For the love of God, go to #bot-commands

slate swan
#

oops i thought it was bot commands lmao

slate swan
upbeat otter
slate swan
#

so it doesn't need the data to run cogs? I should run cogs a different way? this way it does a separate api call?

upbeat otter
sage fern
#

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='>', intents=intents)

@bot.command()
async def ping(ctx):
await ctx.send('pong')

bot.run('token')

Would this work?

glad cradle
#

it should work

pulsar bridge
#

How does one create an on_error event listener for application commands?
Specifically one dealing with the CommandOnCooldown error instance.
This is what I have so far...

@client.event
async def on_application_command_error(error):
    if isinstance(error, discord.app_commands.errors.CommandOnCooldown):
        time = error.retry_after
        time = int(time)
        '''Irrelevent Code'''
        await error.channel.send(f'{(str(ctx.command)).capitalize()} is still on cooldown for {hours} hours, {minutes} minutes and {seconds} seconds!')

But it ain't triggering.
I've tried it with:
on_command_error on_error on_application_error on_application_command_error
Ideas?

slate swan
#

anyone know how I can put three buttons next to each other like that

naive briar
#

Or it has enough space to put there

pulsar bridge
void arch
#

How to add callback to Select menu?

naive briar
unkempt canyonBOT
#

@error(coro)```
A decorator that registers a coroutine as a local error handler.

This must match the signature of the [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.on_error "discord.app_commands.CommandTree.on_error") callback.

The error passed will be derived from [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError "discord.app_commands.AppCommandError").
cold sonnet
#

chocodile or crocolate

#

???

slate swan
#

Chocolagator

cold sonnet
#

damn you suck at this

#

no

slate swan
#

😔

cold sonnet
slate swan
#

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

slate swan
#

Hello

#

An exception has occurred while executing command delete_verification:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord_slash/client.py", line 1353, in invoke_command
await func.invoke(ctx, **args)
File "/home/container/.local/lib/python3.10/site-packages/discord_slash/model.py", line 210, in invoke
return await self.func(*args, **kwargs)
File "/home/container/nitro.py", line 121, in delete_verification
if database_verif.get_verification(guild, role_id) is not None:
File "/home/container/database_verif.py", line 20, in get_verification
cursor.execute(query, (guild_id, role_id))
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.

#
@slash.slash(name = "delete_verification", description = "Delete verification and channel")
async def delete_verification(ctx, role_id):
    guild_id = ctx.guild.id
    guild = ctx.guild
    if (not ctx.author.guild_permissions.ban_members):
        await ctx.send(f"You are not authorized to use this command {ctx.author.mention}")
        return
    if database_verif.get_verification(guild, role_id) is not None:
        database_verif.remove_verification(guild_id, role_id)
        channel = discord.utils.get(guild.text_channels, name="verification")
        await channel.delete()
        await ctx.send("The verification is removed successfully")
    else:
        await ctx.send("The verification is not in place")```
#
def remove_verification(self, guild_id : int, role_id : int):
        cursor = self.con.cursor()
        query = "DELETE FROM verif WHERE guild_id =? AND role_id =?;"
        cursor.execute(query, (guild_id, role_id,))
        cursor.close()
        self.con.commit()```
#

you can help me

#

?

naive briar
slate swan
naive briar
#

With what query

#

Is my question

slate swan
#

This is SQlite

naive briar
#

YES? I already know

#

But with what query did you use to create the tabel

slate swan
# naive briar But with **what query** did you use to create the tabel
import os
import sqlite3

class Verification:
    def __init__(self, database_name : str):
        self.con = sqlite3.connect(f"{os.path.dirname(os.path.abspath(__file__))}/{database_name}")
        self.con.row_factory = sqlite3.Row

    def add_verification(self, guild_id : int, role_id : int):
        cursor = self.con.cursor()
        query = "INSERT INTO verif (guild_id, role_id) VALUES (?, ?);"
        cursor.execute(query, (guild_id, role_id))
        cursor.close()
        self.con.commit()

    
    def get_verification(self, guild_id : int, role_id : int):
        cursor = self.con.cursor()
        query = "SELECT * FROM verif WHERE guild_id =? AND role_id =?;"
        cursor.execute(query, (guild_id, role_id))
        result = cursor.fetchone()
        cursor.close()
        return result

    def get_role_id(self, guild_id : int):
        cursor = self.con.cursor()
        query = "SELECT role_id FROM verif WHERE guild_id =?;"
        cursor.execute(query, (guild_id,))
        result = cursor.fetchone()
        cursor.close()
        return result[0]

    def remove_verification(self, guild_id : int, role_id : int):
        cursor = self.con.cursor()
        query = "DELETE FROM verif WHERE guild_id =? AND role_id =?;"
        cursor.execute(query, (guild_id, role_id,))
        cursor.close()
        self.con.commit()```
naive briar
#

The query that was used to create the table

#

I don't see it in that code

slate swan
#

I created it by hand in the sqlite studio application

#

You can help me ?

vocal snow
slate swan
leaden dagger
#
async def button_callbacken(interaction):
        await interaction.response.send_message("Message")

Can someone help me
I have a button currently sends a message after pressing but i want to change it.
After I press the button must trigger another command (a select menu)
how can i connect them

slate swan
vocal snow
slate swan
vocal snow
#

And in your query you're passing a str

#

Also.can you print(type(guild_id)) before making the query?

rare echo
#

why r u opening the file

vocal snow
#

this kinda defeats the whole point lol

#

you're not actually using environment variables

vapid grove
#

How to make the slash command parameter required instead of optional?

naive briar
#

Don't set the default value

upbeat otter
slate swan
#
async def on_guild_join(guild):
    test = guild.channel.create_invite()
    channels = bot.get_channel(UNESI ID OD TVOG KANALA)
    await channels.send(f"{test}")

Ignoring exception in on_guild_join Traceback (most recent call last): File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 377, in _run_event await coro(*args, **kwargs) File "/home/container/app.py", line 32, in on_guild_join test = guild.channel.create_invite() AttributeError: 'Guild' object has no attribute 'channel'

#

Any who can help?

upbeat otter
#

and you should not do what you're trying to do here

stable nimbus
#

ikr

upbeat otter
slate swan
stable nimbus
upbeat otter
slate swan
stable nimbus
# slate swan K ty

@bot.event
async def on_guild_join(guild):
test = guild.channel.create_invite()
channels = bot.get_channel(UNESI ID OD TVOG KANALA)
await channels.send(f"{test}")

#

so the bot.get_channel

#

are you trying to get a channel with that name?

slate swan
#

I forgot await

upbeat otter
upbeat otter
#

nice answer

stable nimbus
#

ty?

upbeat otter
#

welcome?

slate swan
#

🧠

upbeat otter
#

normal logging would be printing stuff

slate swan
#

For logs

upbeat otter
#

huh

slate swan
#

"tos"

quick gust
#

you're violating the user's privacy

upbeat otter
#

I'm not even arguing just forgive me

quick gust
#

logging the name is fine, but not invite links to their server

slate swan
quick gust
#

try to read, "violating the user's privacy"

#

thats what ure doing with "1 invite"

upbeat otter
void arch
# slate swan same as button

The interaction fails, no error, just the text on discord that it fails
edit:nevermind, I forgot to link the callback

slate swan
#

aliases commands works only with command.commands in COGS ?

tacit horizon
#
@client.command()
async def hi(ctx):
    await ctx.reply("hi")    
    

@client.command()
async def hii(ctx):
    hi(ctx)

why i cant do this

rare echo
#

invoke

tacit horizon
#

whats that

limpid otter
#

is it possible to make a global error handler that will affect all commands, if the user_id is not in the database, then it would give an error, otherwise you don’t want to write a check in all commands?

tacit horizon
naive briar
unkempt canyonBOT
#

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

Calls a command with the arguments given.

This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.

Note

This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.

You must take care in passing the proper arguments when using this function...
slate swan
#

yo im new with cogs im trying to understand but i have error that i dont know how to fix

naive briar
#

You need setup function

slate swan
#

where

naive briar
#

Just run it, see what happens

slate swan
#

i ran it

#

no command named 'hello'

golden portal
#

add_cog is async, you need to await it, also you load extension by bot.load_extension, you shouldn't import the function

quick gust
shrewd apex
#

lol ducky_devil

quick gust
golden portal
#

dpy 2.0 requires setup to be async

quick gust
naive briar
vale wing
#

!pypi python-dotenv when the

unkempt canyonBOT
fading marlin
vale wing
#

Yeah they should just await it

tacit horizon
#

how to get interaction author name

vale wing
#

I am gonna teach you how to get that info from docs

#

First of all, check attributes of Interaction class

#

@tacit horizon

#

!d discord.Interaction

unkempt canyonBOT
#

class discord.Interaction```
Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.

New in version 2.0.
tacit horizon
#

ok

vale wing
#

Ok now, which of them do you think represents the interaction user?

shrewd apex
#

tip: answer is in the question

tacit horizon
#

user

shrewd apex
#

🎉

tacit horizon
#

The user or member that sent the interaction.

Type
Union[User, Member]

shrewd apex
#

yes

tacit horizon
#

Ohhh

#

but whats Union

fading marlin
#

it means that it can be any of those 2 instances

tacit horizon
fading marlin
#

no

#

lowercase

tacit horizon
#

ok

#

Got it

vale wing
# tacit horizon Got it

Great now check attributes of the discord.User class and find out which represents the name

vale wing
#

👏

tacit horizon
vale wing
#

Congratulations now you can use docs for finding information

tacit horizon
#

Yeee

#

Thanks

#

now discord doc making sense for me 😄

sage fern
# glad cradle it should work

it didn't work it showed this intents.message_content = True
AttributeError: 'Intents' object has no attribute 'message_content'

fading marlin
#

update your wrapper

void arch
#

How to do the ghost message thing, basicly a "message" that only targeted user can see and has that little dismiss text that makes it disapear, like some ones in slash commands that are used for errors
something like this, but without this glow, just a message

fading marlin
#

they're called ephemeral responses

void arch
#

ok

fading marlin
#

!d discord.InteractionResponse.send_message you have to set the ephemeral keyword argument to True

unkempt canyonBOT
#

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

Responds to this interaction by sending a message.
void arch
#

thanks

void arch
#

If I want to check if the user that interacts with Interaction I should use Interaction.user to compare, yes or no?

sage fern
white citrus
#

How can I get all "_id"`s from a table so that they are in a list with aiosqlite

vale wing
void arch
#

I have messages array provided by ctx.channel.history
how do I check for all of them if they are not older than 14 days

slate swan
#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destination’s message history.

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

Examples

Usage...
slate swan
#

just use the after kwarg?

void arch
# slate swan just use the after kwarg?

My idea is that I fetch x messages, filter ones that are not older than 14 days to one array, filter ones that are older than 14 days to another one, bulk delete them(I accounted for 100 at time limit) and then fetch and delete rest of them, that is why I want to filter out them from already fetched array and not with kwarg

slate swan
#

use the filter function and seperate the messages that are under 14 days by checking message.created_at

#

!d filter

unkempt canyonBOT
#

filter(function, iterable)```
Construct an iterator from those elements of *iterable* for which *function* returns true. *iterable* may be either a sequence, a container which supports iteration, or an iterator. If *function* is `None`, the identity function is assumed, that is, all elements of *iterable* that are false are removed.

Note that `filter(function, iterable)` is equivalent to the generator expression `(item for item in iterable if function(item))` if function is not `None` and `(item for item in iterable if item)` if function is `None`.

See [`itertools.filterfalse()`](https://docs.python.org/3/library/itertools.html#itertools.filterfalse "itertools.filterfalse") for the complementary function that returns elements of *iterable* for which *function* returns false.
lethal creek
#

Hello, I'm hoping to get some help on a project I'm working on.

I'm building a discord bot that will allow members to connect to Strava, pull their activities and then display information in certain ways (like weekly, monthly, yearly leaderboards for example).

My issue right now is with authenticating with Strava. I've tinkered with the Strava API previously on a Flask project that I was working on last year, but there I used the requests_oauthlib library to handle the sending the request and then getting the access code from the redirect.

I'm trying to get my bot to handle this, but I'm lost . I can have it display the link to the user, but then I haven't figured out how to get the data from the redirect_url aside from having the user copy/paste it. I'd rather not rely on that.

Is there a better way? Any advice/hints would be really helpful. Much appreciated.

slate swan
slate swan
slate swan
#

so what would be the best way to load extensions? I followed a few videos and used this, but what if I wanted to organize them more. i.e. folder/subfolders/files.py?


        for cog_file in settings.COGS_DIR.glob("*.py"):
            if cog_file.name != "__init__.py":
                await bot.load_extension(f"cogs.{cog_file.name[:-3]}")
#
for subdir in os.listdir("main_cog_directory"):
    # ignore files and folder with a continue, example:
    # if subdir = "__init__.py": 
    #     continue
    for module in os.listdir(subdir):
        await Bot.load_extension(f"main_cog_directory.{subdir}.{module[:-3]}")
``` would be the simplest way
#

i noticed the second loop is broken lol, it would be "main_cog_directory/"+subdir inside listdir^

#

thank you! do i need to define the subdir/module via a command then? or with this being a for loop, it will just complete these based on the directory?

#

os.listdir returns a list, subdir is a member of the list per iteration

#

same goes for module

#

you'll have to mention your main cog folder path inside the first listdir

#

so i have in my settings
BASE_DIR = pathlib.Path(__file__).parent
COGS_DIR = BASE_DIR / "cogs"
i'd just change the second one to be
main_cog_directory = BASE_DIR / "cogs" then technically?

#

yep that should do

#

ty!

sick birch
lethal creek
slate swan
#

one more question. for the docs.

    async def ping(ctx):
      await ctx.send("pong")

so for commands, it always needs ctx, minimal, to work... right? then anything after ctx, is considered a string or integer based on what i define them as, but they can't be the prefix... right?

sick birch
#

I hate to say this - but your hands are a bit tied here 😦

golden portal
lethal creek
sick birch
sick birch
lethal creek
sick birch
#

Unless you hack the library into listening for custom dispatches

lethal creek
#

From my understanding:

def check(msg):
    return (
        msg.author == ctx.message.author
        and msg.channel == ctx.channel
        and "https://localhost/exchange_token" in msg.content
    )

All this really does is:

  1. check that the author of the submitted message (after the discord bot sends out the link for them to auth to) is the original author.

  2. Make sure we are still in the right channel

  3. Make sure that whatever message was submitted has the portion of the url I know should be there.

Correct?

sick birch
#

Looks like

https://localhost/exchange_token?code=some_code_here

Is that correct?

sick birch
#

Then yeah, what you said is correct. You'll have to parse out the code yourself
Or use something like urllib, which is part of the stdlib fyi

lethal creek
#

I really appreciate all the help. Especially if you're in the east coast. It's almost midnight here.

sick birch
sick birch
lethal creek
#

I'd like to take a crack at getting it working myself first. I'm almost 100% positive that the issue is in referencing the wrong objects.

But considering how late it is, I'll probably leave it for morning.

slate swan
#

Just post the traceback it's likely an easy fix

sick birch
#

Always great to tackle it yourself first.
If you need help with that tomorrow feel free to open up a help post in #1035199133436354600 and ping me 😄

#

(But like y9 mentioned, if you want to get it out of the way, we can help you out now as well, up to you)

slate swan
#

Hey robin I haven't really checked out discord.py buttons you know any good tutorials on them?

sick birch
slate swan
upbeat otter
#

,

sick birch
#

Nah they can be sent in response to regular prefix commands as well

#

The response to the button however has to be an interaction

#

Though usually you want to tie them in with application commands for the best user experience

lethal creek
#

At the expense of feeling even sillier:

I can just copy/paste the whole traceback? Is there a specific format or do I just ctrl-c/ctrl-v it?

sick birch
#

That's exactly what we want you to do

#

!pastebin if it's too long for discord

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.

lethal creek
sick birch
slate swan
#

I thought it was ctx.author

sick birch
#

ctx.author is a shortcut to ctx.message.author i believe

#

Still odd, nonetheless

slate swan
#

Could you show the code for that command perhaps, Fallennekho3?

sick birch
#

Yes please. Codeblock it here if it's short, or pastebin like before if it's long

lethal creek
#

That was how I had it first and got the same error.

This has been happening all day with stuff, for example ctx.send won't work, but when I switch it to ctx.channel.send it does, which I found through the docs.

slate swan
lethal creek
#

2.1.0

sick birch
#

That's not good.
Actually, can you copy paste your entire code into a !pastebin? (it will probably be too long for discord)

#

(The version is fine, I was referring to it being funky)

slate swan
lethal creek
sick birch
shrewd fjord
#

Hey robin, long time no see :3

sick birch
#

Just a matter of faulty naming

sick birch
slate swan
lethal creek
sick birch
#

!d discord.Interaction @lethal creek discord.Interaction objects differ slightly from commands.Context objects

unkempt canyonBOT
#

class discord.Interaction```
Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.

New in version 2.0.
sick birch
shrewd fjord
sick birch
#

If you'll notice it's a slash command

shrewd fjord
#

So u completed rust?

sick birch
#

Just starting out, in fact

#

Still got lots to learn

shrewd fjord
#

Oh i thought u finishing it alr xd

shrewd fjord
sick birch
#

I don't know if I could ever finish a language like Rust, haha

sick birch
#

Same deal on line 38

lethal creek
#

I really want to make sure I understand, but my brain feels like molasses :

It doesn't really matter what I call it, but with discord bots ctx means I should be using a context object, and those have distinct commands from the interaction objects?

So the issue is that what I have written in places is expecting a context object but is calling interaction attributes, hence why I'm getting my none type error.

So if I just switch something like "ctx.author" to the appropriate attribute for the interaction I should be fine?

sick birch
#

How you have it currently, you have a ctx: discord.Interaction which is really an interaction disguised as a context.
When you try calling methods you normally would on a context, you're actually accessing those methods on an interaction (which of course, don't exist)

#

Fortunately it's pretty simple and a 1 to 1 mapping between commands.Context and discord.Interaction

lethal creek
#

Awesome.

I was trying to print out what the output from each of these attributes, but it kept crashing regardless. When in doubt, I try to print out each of my objects/variables to know exactly what it looks like.

#

Question though: When should I use which?

For example, I imagine if I'm using commands I should be using interactions, since I'm interacting with the bot?

sick birch
#

What sort of commands? Text-based or slash commands?

slate swan
#

you can just use type annotations for your ide to do autocompletes and warn if you're using wrong member of the class

sick birch
#

Text-based commands will use a context
Slash commands will use an interaction

slate swan
lethal creek
#

I really appreciate all the help, and adding more things to my reading. I definitely need to understand these differences better.

sick birch
lethal creek
#

Finding this discord has been a god send, honestly.

sick birch
#

Some other advise I have in your code:

  • sqlite3 is blocking - you don't want to be using blocking libraries in your code. Switch to something like aiosqlite while your codebase is still small and easy to migrate
  • You can use name = interaction.user.name instead of str(ctx.user).split("#")[0] (I'm assuming this part comes from a youtube tutorial)
  • You don't need to int(ctx.user.id), discord_id = ctx.user.id will do just fine
  • I would also not recommend creating a new connection for each command. Rather, you want a global connection and get cursors from there as you need it
  • Syncing should be done in setup_hook rather than in on_ready
#

You can always open a help channel in #1035199133436354600 or ask here and someone will help you out, if you need help with any of those aforementioned improvements

lethal creek
sick birch
lethal creek
#

Very much appreciated @sick birch and @slate swan . You've both been super helpful!

Have a great night (or whatever fits best for your locale)

upbeat otter
flint hare
#

which bot can i use to upwork clients?

slate swan
vestal crescent
#

I need help

naive briar
#

Then ask it

upbeat gust
slate swan
#

sometimes when i load my vscode, i get this error when i try and do pip install...
[Errno 2] No such file or directory i'm just using powershell btw

slate swan
#
PS E:\!python\Bot Python Template> python pip install requests
C:\Users\Keiraxlicious\AppData\Local\Programs\Python\Python310\python.exe: can't open file 'E:\\!python\\Bot Python Template\\pip': [Errno 2] No such file or directory
upbeat gust
#

py -m pip

#

Why are you installing requests for your discord bot though?

slate swan
#

don't I have to install them to run it local to test things?

upbeat gust
#

..?

slate swan
#

you get an error saying Import "requests" could not be resolved in vs when you go to run the main.py... so u have to install them is what I was taught from videos.

#

no?

naive briar
#

Let me guess, YouTube tutorials?

slate swan
#

yup and a skillshare one too

#

the skillshare one has you add them to a doc for heroku to run them.

upbeat gust
#

If you really need to make requests you should be using aiohttp

slate swan
#

cause idk what i'm doing? 🤣

upbeat gust
slate swan
naive briar
#

!d aiohttp

unkempt canyonBOT
#

Common data structures used by aiohttp internally...

naive briar
#

Pretty sure they have some example in their website

upbeat gust
upbeat gust
#

Why do you need it?

slate swan
#

use httpx/aiohttp

#

dont use requests

upbeat gust
#

I've already said that,I don't think they even need it anyway

slate swan
#

show code

slate swan
# upbeat gust Why do you need it?

idk yet, depends on what all it can do. like generate images from certain websites like for waifus, or can it grab data from a user# that's registered on tracker.gg/valorant for their rank
or does this allow api integration and if I have an api key for notion, valorant, apex... w/e can it integrate with those? to be frank, idk what and of these packages do, theres too many and if one person says to use requests and u say to use aiohttp... like how am i supposed to know what 1 can do and what 1 can't? just doesn't make sense to me.

#

use any http client

sick birch
#

@slate swan discord.py uses aiohttp internally so it's a dependency: you install discord.py you also install aiohttp, it's recommend to use aiohttp over requests

upbeat gust
quick gust
#

and the more you use different modules the faster ull understand and remember how each is different

upbeat gust
#

what

quick gust
#

Responding to the end part of their question

slate swan
shell wing
#

Is it possible to fetch a button class or a dropdown class from a diff cog ?

slate swan
#

you mean import it?

shell wing
#

yes and use it ofc

slate swan
#

use the import statement and create an instance of the class?

upbeat otter
shell wing
#

it doesnt matter if the cog is in a folder right ?

upbeat otter
#

well it does

#
from folder.diff_cog import ButtonClass
shell wing
#

ah alr

#

do i need to load this cog too ? a cog only with class(s) ?

slate swan
#

why is it a cog then just use a simple file

shell wing
#

simple file as in ?

slate swan
#

any_file_name.py ??? doesn't need to be an extension

shell wing
#

i aint treating it like a cog-

#

not loading it or anything

shell wing
#

i got a diff project in which i need to do it with a cog too so thats why asking

slate swan
slate swan
#

so you'll have to do the path joining manually

#

pathlib won't do that

slate swan
#

I forgot how to do this with bare requests, but how do I retrieve every message from a channel?

#

You probably know, @slate swan

naive briar
slate swan
#

in discord.py I would just do

[message async for message in channel.history(limit=None)]

but i'm not sure how with just bare requests

#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destination’s message history.

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

Examples

Usage...
slate swan
#

I'm looking for the actual code of that method

slate swan
slate swan
slate swan
slate swan
slate swan
pulsar kettle
#

Hiya, I know discord already has a default /timeout command but I want to be able to add one to my discord.py bot but have no idea what I’m doing. I’ve tried looking on YouTube, stack overflow, Google, etc. and haven’t found one that works and is compatible with slash commands. Can anyone assist me please?

shrewd apex
#

!d discord.Member.timeout

unkempt canyonBOT
#

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

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

You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_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").
shrewd apex
#

!pypi time-str

unkempt canyonBOT
shrewd apex
#

!d discord.ext.commands.Converter

unkempt canyonBOT
#

class discord.ext.commands.Converter(*args, **kwargs)```
The base class of custom converters that require the [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") to be passed to be useful.

This allows you to implement converters that function similar to the special cased `discord` classes.

Classes that derive from this should override the [`convert()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Converter.convert "discord.ext.commands.Converter.convert") method to do its conversion logic. This method must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").
shrewd apex
#

that should be about it

slate swan
#

whats the best way to append user's info? like append their pfp and nickname to files on github or whatever might be obtainable for another bot to grab the info?

pulsar kettle
#

Trying to add a lockdown command to my bot, but it doesn't change the permissions of the everyone role. Please help <3

@bot.tree.command(name='lock', description='Locks a channel')
@has_permissions(manage_channels=True)
async def lockdown(interaction: discord.Interaction):
    guild = interaction.guild
    await interaction.channel.set_permissions(interaction.guild.default_role,send_messages=False)
    embed = discord.Embed(title=(f'{interaction.channel.mention} + " ***is now in lockdown.***'), color=0xf6ff00)
    await interaction.response.send_message(embed=embed)
#

also in the embed it says the channel ID instead of the name

slate swan
#

how can I turn a tool into a bot with /commands

naive briar
unkempt canyonBOT
#

await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sets the channel specific permission overwrites for a target in the channel.

The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that belongs to guild.

The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.

If the `overwrite` parameter is `None`, then the permission overwrites are deleted.

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

In the description?

quick gust
#

.name

upbeat otter
upbeat otter
naive briar
#

I'll test that 🧐

upbeat otter
#

yeah pls thanks

slate swan
# upbeat otter what exctly are you trying to achieve? like in what manner should you store the ...

so i wanted to make animated alerts on streamelements for specific guild.id's when someone joins the discord the bot's in. so while i was waiting for a response, i've been looking into aiohttp and pil? to be able to do image related stuff?
lets say i have a default 200x200 px image and a default text. just when someone joins it, it overwrites the previous. i just want the data to append the info stored since I can't have it append something locally if it's running on a server... so github was my first idea...

waxen granite
#

how do i send msg if the erroris nonetype? try and except?

slate swan
quick gust
waxen granite
#

okay

upbeat otter
#

if you want to upload things and access them from somewhere else, you might wanna use a cloud db, that's the easiest imo

quick gust
slate swan
#

but if i'm using like heroku to host my bot, it won't be able to append files on my pc... which is why i mentioned online services

quick gust
#

I meant, are u running the bot on your computer?

slate swan
quick gust
#

I see, well yeah then you can use a cloud database as Ash said. I'm not entirely sure how heroku works

upbeat otter
upbeat otter
quick gust
#

oh damn

upbeat otter
slate swan
#

i have it linked to github so i thought the init's push's could just overwrite what gets saved, but wasn't sure how it would send data from heroku back to github where it initializes the bot from...

slate swan
#

any suggestions?

upbeat otter
#

something's pushed if you have the feature enabled ofc

slate swan
#

true....

upbeat otter
# slate swan any suggestions?

I'd personally use the deta databases since they're truly easy to interact with
they have a databases for Drive and a JSON-based database too (JSON dbs have a storage of 10gb and the drive also has 10gb I suppose)

slate swan
#

nosql = cringe

upbeat otter
slate swan
#

yes

upbeat otter
#

ok

slate swan
upbeat otter
#

databases are cringe 😔

slate swan
#

^ use paper

#

just go back to stone age and use hammers and chisels at that point

#

just develope a good memory

upbeat otter
#

Just don't do anything and wait for death

slate swan
upbeat otter
#

"don't do nothing" 😔 why even borrow

slate swan
slate swan
upbeat otter
#

that's not boomer type lmao

#

working smarter is actually better

slate swan
#

not working at all better

upbeat otter
#

you do lots of work everyday, so you shouldn't be saying that

slate swan
#

technically speaking my displacement vector is (0,0,0) so nah

#

🤣

waxen granite
#
embed = discord.Embed(icon = member.display_avatar, title = f"Member Joined", description = f"{member.mention}({member.name}) joined the server.\n\n", color = discord.Colour.random(), timestamp = datetime.datetime.utcnow())```
whats wrong here?
slate swan
# upbeat otter I'd personally use the deta databases since they're truly easy to interact with ...

ok, so how does this cloud work? i installed deta package,
then it says


# initialize with a project key
deta = Deta("project key")

# create and use as many Drives as you want!
photos = deta.Drive("photos")
photos.put("my_first_car.png", path="./my_first_car.png")

so would i just do like...
await self.client.photos.put(image_path, member.avatar_url, content_type="image/png")
await self.client.text.put(text_path, member.name, content_type="text/txt")
? aside from the try-except statement handlers.

upbeat otter
#

lemme grab the link rq

slate swan
#

thank you

upbeat otter
upbeat otter
#

you're welcome

slate swan
distant tree
#

anyone down to help me come up with a gameplan to make a transaction bot (examples in screenshots)

#

the current bot is not it

#

hoping to make a better more streamlined and error free alternative

#

it would be server specific

#

i'd assume a db is needed for data that needs to be persistent

#

(like the bot not forgetting user a owns team a, and there are these players on team a)

naive briar
#

Also the icon arg needs a string of a url

#

Not asset

upbeat otter
waxen granite
#

how do you get banlist?

distant tree
upbeat otter
unkempt canyonBOT
#

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

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

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

Examples

Usage...
waxen granite
#
banList = await member.guild.bans()```
i used to do this
naive briar
#

!d discord.Guild.bans

unkempt canyonBOT
#

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

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

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

Examples

Usage...
upbeat otter
#

oof

waxen granite
naive briar
distant tree
naive briar
#

(or iterator)

#

There's an example in the docs

upbeat otter
#
banList = [async for banned_user in Guild.bans()]

😔