#discord-bots

1 messages ยท Page 172 of 1

distant tree
#

looking for a sense of direction on this

#

that's what i was thinking lol

rare echo
#

i mean yes a db would be a very big good thing to do, also changing it from having author in footer and description, you can clean it up by removing the bot name from the top, seeing as the bot sends the message

distant tree
upbeat otter
rare echo
quick gust
#

how do I add a description to an argument of a slash command?

rare echo
#

ohhhh

#

i misread 100%

distant tree
upbeat otter
rare echo
quick gust
naive briar
unkempt canyonBOT
#

@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.

Example:

```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
    await interaction.response.send_message(f'Banned {member}')
```  Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
upbeat otter
#

that's for dpy

distant tree
#

used em before

quick gust
#

what about disnake?

naive briar
#

๐Ÿคท

upbeat otter
#

forgot

supple ridge
#

how can i get the value of total iv using regex?

upbeat otter
rare echo
#

my b g

naive briar
#

He said argument

quick gust
rare echo
#

man its early for me

distant tree
# rare echo yeah i got ya

yeah that's from a private user unwilling to share reference code, i was originally just going to fix the issues for him, but cause yk, i'm jus going to make an alternative

naive briar
rare echo
#

ill be functioning soon ๐Ÿ˜ฎโ€๐Ÿ’จ

rare echo
quick gust
slate swan
# quick gust for an argument

its much simpler ```py
async def command(inter, argument: str)-> None:
"""
Command Description

Parameters
----------
argument: talk about using decorators lmfao
quick gust
#

mhm nice nice

upbeat otter
slate swan
upbeat otter
#

yes

#

but describe ๐Ÿ’€

supple ridge
upbeat otter
#

let's not talk about that

slate swan
#

don't like that style , they could have either made the complete argument using decorator ( like lightbulb does ) or complete argument based options ( function signature )

quick gust
rare echo
#

wouldnt be a hard recreate, maybe just a bit tedious

supple ridge
#

@naive briar can you elaborate on how can i use for loop? pithink

distant tree
upbeat otter
naive briar
#

Wait, did Discord changed mention colour

#

Nvm

open karma
#

MY CODE

c.execute(f"INSERT INTO auctions (name, offer, seller, channel) VALUES ({data[0].value}, {data[2].value}, {interaction.user.id}, {channel.id})")

THE ERROR

Ignoring exception in modal <__main__.AuctionModal object at 0x000001FE0F4EEDD0>:
Traceback (most recent call last):
  File "C:\Users\AngelosKehayoglou\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\modal.py", line 341, in dispatch
    await value.callback(interaction)
  File "c:\workspace\python\Bots\marketplace\main.py", line 69, in callback
    c.execute(f"INSERT INTO auctions (name, offer, seller, channel) VALUES ({data[0].value}, {data[2].value}, {interaction.user.id}, {channel.id})")
sqlite3.OperationalError: no such column: aaa
#

i have a modal where i can type something

#

in this example i typed in "aaa"

rare echo
#

which doesnt exist

supple ridge
open karma
#

and now where i try to insert it into a database it says that the column doesnt exist?

open karma
#

how can it "not exist"?

open karma
#

i did read it

#

i still dont understand it

naive briar
#

Don't use f-string in SQLite queries

open karma
#

oh okay

naive briar
#

Use placeholder, or something I forgot

open karma
#

should i use ?

slate swan
#

!sql-fstrings yes

unkempt canyonBOT
#

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

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

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

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

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

See Also
โ€ข Python sqlite3 docs - How to use placeholders to bind values in SQL queries
โ€ข PEP-249 - A specification of how database libraries in Python should work

open karma
#

?, ?, ?, ?

open karma
open karma
slate swan
#

if they are the only columns in the table you dont even need to mention them at all

open karma
#

btw, is that pfp from adventure time? ๐Ÿ˜‚

open karma
winged linden
#

Is there a way to run code when the bots is shutting down?
I want to edit the name of a voice channel when the bot stops running

waxen granite
#
        async for ban in guild.bans():
            banList = ""
            for ban in banList:
                if ban[1] == member:
                    title = f"Member Banned"
                    desc = f"{member} has been banned from the server for {ban.reason}"```
still something wrong :3
winged linden
waxen granite
#

nah

winged linden
#

just anyway

slate swan
winged linden
#

im trying to make a status channel and it needs to change to off if the bot isnt online

cloud dawn
winged linden
#

ah I see

#

Ill just pray they don't close the bot

waxen granite
ornate kite
#

can you run 2 clients in one code?

winged linden
#

why would you do that

cloud dawn
unkempt canyonBOT
#

discord.on_member_ban(guild, user)```
Called when user gets banned from a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

This requires [`Intents.bans`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.bans "discord.Intents.bans") to be enabled.
cloud dawn
ornate kite
#

k ty

torn sail
cloud dawn
cloud dawn
waxen granite
cloud dawn
ornate kite
# cloud dawn Yes.

at the end of he code i have

discord.run('token') (discord client)
client.run() (second client)

torn sail
naive briar
#

.run is blocking

waxen granite
ornate kite
naive briar
#

You could use .start with asyncio.gather

waxen granite
#

i am tryng to to use on_member_leave to send a msg when the user gets banned and in the same event when the member leave it sends a seperate msg

naive briar
#

Why are you trying to run 2 bot instances in the same time anyway

cloud dawn
ornate kite
#

how

cloud dawn
ornate kite
#

i cant code lol

naive briar
cloud dawn
#

Just use create_task.

naive briar
#

I'm already to forget stuff about asyncio

ornate kite
naive briar
slate swan
supple ridge
open karma
#

me again

#

so i cant use f strings in sql statements. but what about {} and .format()

#

does that work?

naive briar
#

I

torn sail
# open karma so i cant use f strings in sql statements. but what about {} and .format()

Do not:
cursor.execute("SELECT * FROM table_name WHERE value = {}".format('peepeepoopoo'))
Do:
cursor.execute("SELECT * FROM table_name WHERE value = ?", ('peepeepoopoo',))

Consider: if a command accepts user input, and they input True; DROP TABLE table_name- The resultant query with format is:
SELECT * FROM table_name WHERE value = True; DROP TABLE table_name which has obvious results.
Utilizing your SQL library's sanitization methods prepares the statement and exclusively inserts the values, without editing the query.
Note asyncpg uses $1, $2, ... for value substitution, mysql-connector, %s, so make sure you know your DB library!
https://xkcd.com/327

slate swan
#

any kind of string interpolation should not be used

supple ridge
slender oracle
#

how can i keep track of how many times a command has been ran by each person?

naive briar
#

Store to a database

slate swan
waxen granite
#
    async def on_member_remove(self, member):
        guild = str(member.guild.id)
        name = member.name + "#" + member.discriminator
        id = str(member.id)
        try:
            print("logid")
            id = self.guildchannels[guild]["logs"]
        except:
            print("no id")
            return
        print("logchannel")
        logChannel = self.bot.get_channel(id)
        print(logChannel)
        title = None
        print(title)
        banList = [ban async for ban in guild.bans(limit=2000)]
        print(banList)
        for ban in banList:
            if member in banList:
                title = f"Member Banned"
                desc = f"{member} has been banned from the server for {ban.reason}"
            else:
                print("log left")
                title = "Member Left"
                desc = f"{member} has left the server"
            print(" log embed formed")
            embed = discord.Embed(title = title, description = desc, color = discord.Colour.random(), timestamp = datetime.datetime.utcnow())
            embed.set_thumbnail(url=member.display_avatar)
            print("log author")
            embed.set_author(icon_url=member.display_avatar, name=name)
            print("log footer")
            embed.set_footer(icon_url= member.guild.icon, text = f"{member.guild}")
            print("log embed sent")
            await logChannel.send(embed = embed)```
it prints till` 'print(title)'`
someone help losing my mind lol
naive briar
#

print doesn't print None object

ornate kite
#

I have the problem that when i want to start the discord client it dosent work, it showes me this in the promt:

โ€ข Fortnite Client ready as FlJILeaks
โ€ข Discord Client ready as None

im working on a fortnite bot that u can controll through discord, but for this i need to run 2 clients and its only run 1

any ideas?

waxen granite
naive briar
#

!e

print(None)
unkempt canyonBOT
#

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

None
waxen granite
#

that

naive briar
#

Nvm

naive briar
waxen granite
slate swan
naive briar
#

And what is it

waxen granite
#

that idk

ornate kite
naive briar
#

You are kidding

#

Read the error, the answer is right there

slate swan
#

!self

unkempt canyonBOT
#

Class instance

When calling a method from a class instance (ie. instance.method()), the instance itself will automatically be passed as the first argument implicitly. By convention, we call this self, but it could technically be called any valid variable name.

class Foo:
    def bar(self):
        print('bar')

    def spam(self, eggs):
        print(eggs)

foo = Foo()

If we call foo.bar(), it is equivalent to doing Foo.bar(foo). Our instance foo is passed for us to the bar function, so while we initially gave zero arguments, it is actually called with one.

Similarly if we call foo.spam('ham'), it is equivalent to
doing Foo.spam(foo, 'ham').

Why is this useful?

Methods do not inherently have access to attributes defined in the class. In order for any one method to be able to access other methods or variables defined in the class, it must have access to the instance.

Consider if outside the class, we tried to do this: spam(foo, 'ham'). This would give an error, because we don't have access to the spam method directly, we have to call it by doing foo.spam('ham'). This is also the case inside of the class. If we wanted to call the bar method inside the spam method, we'd have to do self.bar(), just doing bar() would give an error.

slate swan
#

told ealier, check recent pings

ornate kite
slate swan
#

discord.run is not a thing

ornate kite
#

start or what

waxen granite
slate swan
#

your client object has the run method and it's blocking, any code after it wont get executed

ornate kite
#

is there a way to fix it

slate swan
slender oracle
#

how can i make a program wait a certain amount of time before doing something?

ornate kite
#

im so bad lmao

unkempt canyonBOT
#

coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.

If *result* is provided, it is returned to the caller when the coroutine completes.

`sleep()` always suspends the current task, allowing other tasks to run.

Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.

Example of coroutine displaying the current date every second for 5 seconds:
slate swan
ornate kite
slate swan
#

to get that result

waxen granite
# slate swan and after that? i just sent the condition you need to do what you want to do in ...
        banList = [ban async for ban in guild.bans(limit=2000)]# here is the ban list ///// the code still stucks here
        print(banList)
        for ban in banList:
            if member in banList: # here cehck if the member is in the ban list
                title = f"Member Banned"
                desc = f"{member} has been banned from the server for {ban.reason}"
            else: # here if the member isnt in the ban list 
                print("log left")
                title = "Member Left"
                desc = f"{member} has left the server"
            print(" log embed formed")```
@slate swan
supple ridge
# naive briar `print` doesn't print `None` object

hey i have narrowed it down to
['**hp:**', '80', 'โ€“', 'iv:', '30/31\n**attack:**', '73', 'โ€“', 'iv:', '12/31\n**defense:**', '122', 'โ€“', 'iv:', '25/31\n**sp.', 'atk:**', '65', 'โ€“', 'iv:', '26/31\n**sp.', 'def:**', '31', 'โ€“', 'iv:', '5/31\n**speed:**', '51', 'โ€“', 'iv:', '10/31\n**total', 'iv:**', '58.06%']

now what shall i do to get the last percentage?

naive briar
#

It's like the first thing you will encounter in asynchronous programming

ornate kite
# slate swan to get that result

print(Fore.LIGHTCYAN_EX + ' โ€ข ' + Fore.RESET + 'Discord Client ready as ' + Fore.LIGHTCYAN_EX + f'{discord.user}') but it dosent start the dc bot

naive briar
unkempt canyonBOT
#

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

58.06%
naive briar
#

If it's static then I guess

supple ridge
#

static?

slate swan
supple ridge
slate swan
naive briar
#

Eh, I was about if the embed formatting will stay the same

naive briar
#

If they move the percentage position then it will break

ornate kite
naive briar
#

You should use regex, way neater

supple ridge
slate swan
ornate kite
slate swan
#

or some other app

naive briar
ornate kite
#

its a bot in a game

supple ridge
supple ridge
slate swan
supple ridge
#

I'll try tysm

cloud dawn
# ornate kite can any one send me a little template
import asyncio
from discord import Client, Intents

loop: asyncio.AbstractEventLoop = asyncio.new_event_loop()

class BaseClient(Client):
    def __init__(self) -> None:
        super().__init__(loop=loop, intents=Intents())

    async def on_ready(self) -> None:
        print(self.user.name)

    async def close() -> None:
        await super().close()

panda = BaseClient()
bird = BaseClient()

async def run_panda() -> None:
    async with panda:
        await panda.start(token)

async def run_bird() -> None:
    async with bird:
        await bird.start(token)

if __name__ == "__main__":
    loop.create_task(run_panda())
    loop.create_task(run_bird())
    loop.run_forever()
ornate kite
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.

supple ridge
#

it works tysmmm

waxen granite
cloud dawn
ornate kite
#

TypeError: 'module' object is not callable

#

whats thati just started with py thats why im not good

#

discord = discord.client() TypeError: 'module' object is not callable

slate swan
naive briar
#

Python attributes are case sensitive

unkempt canyonBOT
#

class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

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

New in version 2.0.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
ornate kite
#

can i do discord = discord.Client(intents=intents)

naive briar
#

You are overriding discord module

ornate kite
#

means?

naive briar
#

Change the var name to client or bot

ornate kite
#

kk

naive briar
#

Or anything that's not overriding something important

ornate kite
#

im so sry when its to easy but im to dumb ๐Ÿ˜ฆ

#

command_prefix=prefix, NameError: name 'prefix' is not defined lmao

young dagger
#

How do I edit this command? This command doesn't exist in my current code.

rare echo
#

its default help command, just make a help command and remove the default in the constructor

young dagger
#

@rare echo How do I remove it from the constructor?

naive briar
#

help_command=None

#

In the bot constructor

lethal creek
#

good morning/afternoon/evening,

I'm trying to create a global connection to my database so I can use it across different events. Right now, Google lead me to something like this:
db_con = None
@bot.event
async def on_ready():
if db_con is None:
db_con = await aiosqlite.connect("strava.db")
conn = await db_con.cursor()

#

But I keep that db_con is referenced before assignment. I assume this means that on_ready() is happening before anything else?

My other idea is just to open/close the connections in each command as needed, but that feels tedious.

slate swan
#

!d discord.Client.setup_hook

unkempt canyonBOT
#

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

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

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

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

Warning

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

this gets triggered only once, before the bot runs

ornate kite
#

!d help

unkempt canyonBOT
#

help()``````py

help(request)```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).

This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
supple ridge
#

i have a code with a if else statement this if else statement gives me a percentage value now i wish to use this value outside of this if else statement

#

how can i do that?

#

how to label it as a global variable ;-;

upbeat otter
upbeat otter
unkempt canyonBOT
#

When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.

Instead of writing

def update_score():
    global score, roll
    score = score + roll
update_score()

do this instead

def update_score(score, roll):
    return score + roll
score = update_score(score, roll)

For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.

upbeat otter
#

don't use global here though

supple ridge
crimson mauve
#

Hello, has anyone here ever worked with attachments for message.edit()?

        Embed = discord.Embed(title=f"hello")
        TempFile = discord.File(f"{FilePath}\\TEMP.png", filename="TEMP.png")
        Embed.set_image(url=f"attachment://{FilePath}\\TEMP.png")
        await message.edit(embed=Embed,attachments=TempFile)

I know it's not right because attachments expects an iterable. I'm just not sure how to make what it's expecting.

lethal creek
slate swan
slate swan
#

[TempFile]

ornate kite
#

raise RuntimeError('Event loop is closed') RuntimeError: Event loop is closed

#

cmd promt shows me that error

crimson mauve
#

Ya, it works now.

cloud dawn
lethal creek
crimson mauve
slate swan
#

before your bot is online

lethal creek
# crimson mauve you are trying to set up a task that runs every so X seconds?

No, I'm trying to have 1 global connection open to my database that different commands can access.

Before I was opening connections in each command and then manipulating the database that way. But I'd like to just have 1 open connection and then use that in different commands.

With sqlite3 I could define the connection globally and then use it to create cursors as needed. But with aiosqlite it doesn't work, so I'm trying to figure that out.

lethal creek
#

oh snap, I think I figured it out and I feel silly

crimson mauve
#

Sorry that I'm a little late joining in, but what DB are you running?

lethal creek
#

instead of making it some random variable I tried using the bot object.

lethal creek
crimson mauve
slate swan
#

i dont think that really solves his issue just suggesting something else lol

lethal creek
slate swan
#

yup

crimson mauve
#

It also solves your problems with just defining and calling an engine object.

lethal creek
#

would it prevent my blocking issue, though?

slate swan
#

i create a function that i call in bot.loop.run_until_complete to create db connection by creating a pool. defined as self.db then called using bot.db

crimson mauve
lethal creek
#

So far, I think I've managed to get it to work by using bot.db_con instead of saving it into a random variable

slate swan
#

wait are you having blocking issues using aiosqlite?

crimson mauve
#

I pulled this from the discprd.py examples folder on github

import discord
import asyncio


class MyClient(discord.Client):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    async def setup_hook(self) -> None:
        # create the background task and run it in the background
        self.bg_task = self.loop.create_task(self.my_background_task())

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

    async def my_background_task(self):
        await self.wait_until_ready()
        counter = 0
        channel = self.get_channel(1234567)  # channel ID goes here
        while not self.is_closed():
            counter += 1
            await channel.send(counter)
            await asyncio.sleep(60)  # task runs every 60 seconds


client = MyClient(intents=discord.Intents.default())
client.run('token')

It might not be exactly what you are asking for but it's the function in action.

lethal creek
unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

shrewd apex
slate swan
#

Anyone know why this command isnt working? @client.command() @commands.has_permissions(ban_members=True) async def ban(ctx, member: discord.Member, *, reason=None): await member.ban(reason=reason) await member.send(f"You were banned from the {ctx.guild.name} server for the following reason: {reason}") await ctx.send(f"{member.mention} was banned for reason: {reason}")

slate swan
#

no bot runs fine. The command was working as of December 13th but stopped working a couple weeks ago.

#

what about role hierarchy?

crimson mauve
#

is your bot higher than them?

slate swan
#

its at the top and has admin.

crimson mauve
#

Did you change your command prefix?

slate swan
#

no.

crimson mauve
#

worth a shot

#

ยฏ_(ใƒ„)_/ยฏ

slate swan
#

has anything changed within the bot or server?

#

nah

#

and you double checked everything?

#

yes

#

i havent changed the command at all

crimson mauve
#

Are things wrapped in a try/except:pass?

slate swan
crimson mauve
slate swan
#

do u have a error handler?

#

or catching errors at all

slate swan
#

even with prefix changed still doesnt work.

crimson mauve
#

Try calling a fake command

#

Like !IHDKJHF

slate swan
#

alr

crimson mauve
#

Getting a no command error?

slate swan
#

nah

#

just no response

lethal creek
crimson mauve
#

Is..... is the bot in that server?

slate swan
#

i have a auto role that requires the bot to not send a message which works fine but the other commands dont work

slate swan
#

do any of your cmds work?

#

nah jus auto role

#

oh

#

they was all working the other day

#

well there u go

#

something has clearly changed

crimson mauve
slate swan
#

when i had auto role it was working.

#

is that a cmd ?

#

no

#

it runs whenever a memebr joins

#

yea that working has nothing to do with ur cmds not being processed then

crimson mauve
#

ohhhhhhh, on_message is eating your commands

sick birch
#

!pastebin @slate swan can you pastebin your entire code please?

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
#

yea ive got it bookmarked lmao

sick birch
slate swan
sick birch
#

TL;DR use @client.listen() instead of event

slate swan
#

alr

crimson mauve
#

Don't worry, there ain't too many moon logic pitfalls in discord.py

#

that one has to be the worst.

slate swan
#

thank you.

upbeat otter
crimson mauve
slate swan
#

i somehow skipped dpy in my journey to discord bots lmao

upbeat otter
#

I've never used dpy after that one time I discovered it's so bad ๐Ÿ’€

crimson mauve
#

I like it, it does what I want so far. Its support team on the other hand. I'll just keep my mouth shut.

slate swan
#

yeaaa i started with nextcord and ended with disnake when they released slash commands

upbeat otter
slate swan
#

i tried helpig someone one time and the staff person told me to shut up, timed me out then procedded to give them exactly what i did

crimson mauve
#

Ok, honestly glad to know I'm not just some bitter asshole.

upbeat otter
crimson mauve
slate swan
#

๐Ÿ—ฟ r1 for helping in .gg/dpy
provide the shortest help statement ever with a rtfm command

upbeat otter
slate swan
slate swan
#

for the better. might have to look into it again

#

everyone's switching to furo

slate swan
upbeat otter
slate swan
slate swan
#

their docs are so bad.

#

^

slate swan
#

the commands extension docs are foinu, but Interaction docs suck

#

yup

#

they barely exist

lethal creek
slate swan
#

there's many easier and advanced ones

slate swan
#

that's my current error and client wont actually get retrieved.

crimson mauve
upbeat otter
slate swan
#

would be cool if they named it deta.Base ๐Ÿ’€

upbeat otter
#

There is

#

in the package which is not async

#

deta.Deta.Base
or deta.Base simply

slate swan
#

hm this db looks much better than mongo

#

it uses dictionary only where it's required

upbeat otter
#

imagine using mongo

lethal creek
crimson mauve
lethal creek
#

my tabs are never ending.

slate swan
# upbeat otter instead of `deta.Client` you have to do `deta.Deta`

ok, that fixed one error... ty again...
project_key and base_name are the only things i see as far as credentials... but theres a token you can make in settings? I'm assuming i only need my project name(default) as the base_name and the project key is self explanatory. right?

upbeat otter
#

also I just realized

#

You're putting your images inside a database
shouldn't you be using drive for that? or does it work with that too?

slate swan
#

i was just going to do a test command w/ my alt acct to have a template to go off of.

#

i figured if this can append them, it should be able to insert them as well as a test

#

i'm now realizing that i've been doing the wrong function to insert them tho... ๐Ÿคฃ

solid orbit
#

i am learning to code and the first little project i want is to make a simple discord bot, but i can't find anywhere how to do that.
can somebody give me the code (only to let the bot go online)

slate swan
#

if you are learning to code i wouldn't start with a discord bot or else you will be in for a long ride

lethal creek
#

Yeah, this damn bot has been a bigger challenge than I expected, honestly. But it's been fun

slate swan
ornate kite
#

client.run() bot.start() <- Discord

how can i run 2 clients at the same code

#

its one in fortnite (in game bot) and one discord

sick birch
ornate kite
sick birch
#

Separate them out then

ornate kite
sick birch
#
python discord_bot.py
python fortnite_bot.py
slate swan
#

yo is it possible that a discord bot takes control of a discord account and do a slash command from the discord account?

sick birch
slate swan
#

yes ik it's again tos i won't do it xd i just want to know if it's doable

#

in any case ill do it

#

I don't have the skills, the time and the desire

#

Bots can't invoke slash commands so even if you tried it'd be a no

#

ok

#

wtf

#

ph since 18hours

#

bro let ur dick to rest

ornate kite
#

๐Ÿ’€

ornate kite
sick birch
ornate kite
#

right

sick birch
#

What sort of IPC or other communication pipeline have you set up?

ornate kite
#

wym ๐Ÿ’€ im not so good in py

sick birch
#

It's going to be a bit complex if you want to bots to communicate with each other

#

So set up some sort of communication pipeline

ornate kite
#

i have one in js

sick birch
#

Oh and the bots are written in different languages too?

ornate kite
#

discord + the fortnite bot are written in js

#

now i want to make it with py

sick birch
#

You want to rewrite both in python?

#

Also aren't fortnite bots against Epic's TOS?

ornate kite
#

i coded fn bots since 2020, u cant cheat or smt with them

#

so ig no

sick birch
#

Not just for cheating

#

Many services outright deny automation

#

Such as discord

ornate kite
#

many people have lobby bots

#

and no one of mine is banned or smt

craggy pulsar
#

Hey guys Iโ€™m trying to code a bot that will send alerts to discord if stocks have a cross of Exponential Moving Averages. Iโ€™m brand new to coding and have never done this before. Any help or where to start or what the code would look like would be helpful. Iโ€™ve already made the server and the bot. Just dont know what to code in python to make it actually scan and send alerts to discord.

Thanks!!

shrewd apex
crimson mauve
supple ridge
#

@naive briar how can i get only the top value? and ignore the rest? ur code the one u gave with regex works fine but gives all values

craggy pulsar
# crimson mauve How's it going so far, figuring it out?

Iโ€™m just researching how to even start the code so it scans markets. This is my first time coding and Iโ€™m only doing it cause I couldnโ€™t find any premade ones on the internet๐Ÿ˜‚ so I figured Iโ€™ll just try it myself.

So Iโ€™m just googling how to start any of it right now

slate swan
#

Can i use one commands.group in two different cogs? If yes, then how? Because im getting the The command ... is already an existing command or alias. error.

crimson mauve
#

But, that never stopped alot of us, just expect to hit your head on the wall alot.

crimson mauve
slate swan
#

not command but group

#

anyone have suggestions to get around this?
Invalid Form Body - In content: Must be 2000 or fewer in length.

#

@bot.group()
async def ...

crimson mauve
#

Could upload a .txt file

slate swan
#

useless how?

slate swan
sick birch
slate swan
#

ohh

sick birch
#

What information are you displaying?

slate swan
#

i'm trying to make a list of information like the roles / channels / categories i have. and i had each neatly organized w/ a \n for each line.

crimson mauve
slate swan
#

how can i have it automate the responses to divide each 2k cap line into a new message w/o possibly getting the bot or me limited by discord itself?

crimson mauve
slate swan
#

Yes?

crimson mauve
crimson mauve
# slate swan Yes?
    @commands.command(aliases=["OtherCommandNames"])
    async def CommandName(self, ctx):
slate swan
crimson mauve
slate swan
#

not really...

slate swan
#

c# yes. python, no.

crimson mauve
#

can I see your code?

slate swan
#

sure 1 sec

#

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

white citrus
#

Why is it not definied

crimson mauve
white citrus
#

Ok thanks lmao

crimson mauve
crimson mauve
slate swan
#

ur fine

shrewd apex
white citrus
#
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 489, in _run_event
    await coro(*args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 272, in on_application_command_error
    raise error
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 888, in invoke_callback_with_hooks
    await self(interaction, *args, **kwargs)
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\cooldowns\cooldown.py", line 93, in inner
    result = await func(*args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\bot_info\cog.py", line 187, in stats
    await self.universal_log_embed_slash(interaction)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\bot_info\cog.py", line 50, in universal_log_embed_slash
    log_channel = await self.get_log_channel(interaction.guild.id)
TypeError: BotInfo.get_log_channel() takes 1 positional argument but 2 were given```
#
    async def get_log_channel(guild_id):
        async with aiosqlite.connect("maja.db") as db:
            async with db.cursor() as cursor:
                await cursor.execute('SELECT guild_id FROM setup WHERE guild_id = ?', (guild_id,))
                guild_exists = await cursor.fetchone()
                                
                if guild_exists is None:
                    raise check_error__logchannel_not_found

                else:
                    await cursor.execute("SELECT log_channel FROM setup WHERE guild_id = ?", (guild_id,))
                    log = await cursor.fetchone()
                    return log[0]```
#
    async def universal_log_embed_slash(self, interaction, **kwargs):
        command_mention = nextcord.utils.get(interaction.client.get_all_application_commands(), name=interaction.application_command.name)
        embed = nextcord.Embed(description=f"{interaction.user} used a command", colour=config.blurple, timestamp=nextcord.utils.utcnow())
        
        log_channel = await self.get_log_channel(interaction.guild.id)```
shrewd apex
#

u did something like self.get_log_channels?

#

ah yes in get_log_channel do (self, guid_id)

slate swan
#

i didn't wanna use the discord interface to grab everything one by one. so i just wanted to make it easier with this, plus i can mess around w/ the setup of the "streaming presence" next after I organize my discord id's and stuff.

i'm guessing it would be role_list = "\n".join.len([f"[{role.name}]({role.id})" for role in guild.roles]) for the specific one in question.

white citrus
#

Because he needs it or not?

shrewd apex
#

async def get_log_channel(self, guilf_id):

crimson mauve
slate swan
crimson mauve
shrewd apex
#

remove the .len

crimson mauve
slate swan
crimson mauve
#

I'm going to take

channel_id = ()
member_list = {}
role_list = {}
category_list = {}
channel_list = {}
member_list_data = {}
role_list_data = {}
category_list_data = {}
channel_list_data = {}
``` and see what I can do about compressing it into one dict.
slate swan
#

and just have pages for ea, idk. just spitballing

crimson mauve
#
the_info={}

[Guild][Users]
       [Roles]
       [Categorys][Channels]
#

So, I know the schema can look confusing.

slate swan
slate swan
shrewd apex
#

discord supports ansi encoding

#

about like 7-8 colors and a few backgrounds iirc total like 16

crimson mauve
#

I'll be back in a bit, making a new cog.

slate swan
slate swan
shrewd apex
potent light
solid orbit
#

why does: "python3 -m pip install -U discord.py[voice]" not work?

shrewd apex
#

why are u using delete_after and ephemeral?

potent light
solid orbit
shrewd apex
#

dosent make sense its prone to error

potent light
shrewd apex
solid orbit
potent light
solid orbit
shrewd apex
#

ic its python

potent light
solid orbit
potent light
#

np

shrewd apex
slate swan
potent light
shrewd apex
slate swan
#

also I had a question.
so nightbot, for twitch integration has this in their docs...
Nightbot does not sync subscribers. Discord has a built-in subscription integration with Twitch and YouTube, so the role selection for Subscribers is only used to identify existing subscribers in the server.
So if this is built-in as their docs say, how can I get that information?

shrewd apex
potent light
shrewd apex
shrewd apex
potent light
chilly dove
chilly dove
potent light
chilly dove
#

2.1 is full release so alpha version probably doesnt have it

shrewd apex
#

does your linter show the delete_after kwarg? try to hover your mouse over the method to see the pop up documentation

potent light
potent light
fast lotus
#

how to fix it?

crimson mauve
# slate swan okie dokie, ty for the help ๐Ÿ™‚

looks like I have to run before I can do all of it


import discord
from discord.ext import commands

intents = discord.Intents.all()
bot = discord.Client(intents=intents)

class DataGrab(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.TheData = {}
        self.Page = 0
        self.DataPost = {}

    @commands.is_owner()
    @commands.command()
    async def PartyLikeTheCIA(self, ctx):
        # this Guild object holds all the info you want, now we just need to sift though it.
        self.TheData = ctx.guild
        Embed = discord.Embed(title=self.TheData.name,
                description=f"This Server has \n {len(self.TheData.members)} Users \n {len(self.TheData.roles)} Roles\n and {len(self.TheData.channels)} channels in {len(self.TheData.categories)} categories"
                )

        DataMessage = await ctx.send(embed=Embed)
        self.DataPost[DataMessage] = {"User": ctx.author}

async def setup(bot):
    await bot.add_cog(DataGrab(bot))
slate swan
icy meadow
#

Hello I have created a test website for my bot configuration,I want to ask what is the best way to make everything work correctly, for example: I have a button on my website [Setup Category], how exactly do I make the bot create a category in a guild, it should again run the bot 2nd time (ie two token connection's)?.

crimson mauve
icy meadow
#

I'm looking how I will connect it with the website

crimson mauve
#

What is the site made with?

icy meadow
#

Can i dm you?

crimson mauve
#

The more eyes that see it the more that can help you.

icy meadow
#

Or I create a forum channel

#

Because this is oft

crimson mauve
#

no one is talking but us anyway.

#

Ya... got my DMs shut of for reasons like this.

icy meadow
#

My forum post

crimson mauve
#

Welcome to the first flask tutorial! This series will show you how to create websites with python using the micro framework flask. Flask is designed for quick development of simple web applications and is much easier to learn and use than django. If you are less experienced with python and want to learn how to make websites flask is the right to...

โ–ถ Play video
sick birch
#

Just send a POST request to the appropriate endpoint

#

It's maybe 5 lines of JS

icy meadow
sick birch
#

No need for anything extra

icy meadow
#

There is any example? Video?

sick birch
#

Not that I know of
They all overcomplicate things by bringing in IPC or discord-oauth

#

But it shouldn't be very difficult

icy meadow
#

Something like that?

crimson mauve
crimson mauve
icy meadow
#

As I Said I'm trying to understand how works

icy meadow
sick birch
#

Right. The only URL parameter is the channel ID

#

everything else goes in the request body

icy meadow
#

That's make sense

crimson mauve
icy meadow
sick birch
#

You need to provide your bot's token yeah

#

In the form of

{
  "Authorization": "Bot YOUR.BOT.TOKEN.HERE"
}
icy meadow
#

Ok

sick birch
#

FYI this needs to be in the HEADERS

#

The actual message content and whatnot goes in DATA

icy meadow
#

Got you man

#

Thank you robin!

#

And Zippy

crimson mauve
#

๐Ÿ‘

crimson mauve
#

What's going on with line 420 then?

fading marlin
#

send the full traceback please

#

doesn't look like it?

#

the actual error is missing

#

it does...?

crimson mauve
#

lol

fading marlin
#

your issue occurred in on_interaction apparently, not on_check

crimson mauve
#

but I guess we won't know unless we get the entire log.

slate swan
#

so i edited that portion

#

anyone know why i keep getting this error? Traceback (most recent call last): File "c:\Users\jonah\Downloads\test.py", line 4, in <module> from discord_components import Button, Select, SelectOption, ComponentsBot, interaction ModuleNotFoundError: No module named 'discord_components'

sick birch
slate swan
#

alr

crimson mauve
slate swan
#

any suggestions for making ticket system in discord.py?

crimson mauve
slate swan
#

elaborate.

crimson mauve
#

They are more than likely where you will be storing/accessing your data about the ticket.

slate swan
#

๐Ÿ‘

pulsar kettle
#

Hiya! I'm trying to create a command that adds a role to a member but:

  1. Currently executing the command gives the error discord.app_commands.errors.CommandInvokeError: Command 'role' raised an exception: TypeError: object Role can't be used in 'await' expression
  2. How can I implement code so it checks if a user has that role and it removes it instead?
    Here's the code:
@bot.tree.command(name='role', description='Adds a role to a member')
@has_permissions(manage_roles=True)
async def role(interaction: discord.Interaction, member: discord.Member, role: discord.Role):
    await discord.utils.get(member.guild.roles)
    await member.add_roles(member, role=role)```
chilly dove
pulsar kettle
#

So what do I change it to?

chilly dove
#

well when the function returns its trying to do await Role

sick birch
#

You already have the role (from the function definition)

#

As it's part of the slash command

#

All you need is await member.add_roles(role)

#

To check:

if role in member.roles:
  # user already has that role...
pulsar kettle
#

Aight, add/remove role works great now, thanks guys!
One more quick question: can you tag roles in embeds? Or would I have to keep it as plaintext in the embed?

slate swan
#

i do have a question for embeds. how would i repeat this layout for another project i'll end up doing

hushed galleon
#

looks like an author, description, image, and a broken thumbnail

hushed galleon
pulsar kettle
pulsar kettle
#

Aight thx for your help <3

lethal creek
#

quick question:

Is it good practice to save datetime values in an aiosqlite database as text? Searching through Google told me that aiosqlite doesn't have a datetime or timestamp data type, so I'm thinking I'll just save it as text?

hushed galleon
lethal creek
#

I figured I'd ask here because I'm specifically trying to use aiosqlite to prevent any blocking in the bot. But I can pop over there too

hushed galleon
#

sure, i can elaborate further in that channel

pulsar kettle
#

Creating a purge command, it works, but it doesn't send the response (like it says !Application did not repsond)

@bot.tree.command(name='purge', description='Deletes a specified number of messages from a channel')
@has_permissions(administrator=True)
async def purge(interaction: discord.Interaction, limit: int):
        await interaction.channel.purge(limit=limit)
        embed = discord.Embed(title=(f'Purged {limit} messages'), color=0xf6ff00)
        await interaction.response.send_message(embed=embed)
hushed galleon
#

does it give you a 404 Not Found error in your terminal?

pulsar kettle
#

discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

hushed galleon
#

that means you've exceeded the 3 second time limit for responding to the interaction

#

you can defer() it before doing the purge, and then use the .followup webhook to respond afterwards

sick birch
pulsar kettle
hushed galleon
#

that seems unusually slow

sick birch
#

Hm. That shouldn't be taking more than 3 seconds

pulsar kettle
#

If I purge 2 or more messages, the application doesn't respond

hushed galleon
#

hey wait a minute im noticing the same delay too

pulsar kettle
#

Can you also not purge 2 or more messages?

sick birch
hushed galleon
#

purging multiple messages is fine, but perhaps ill try measuring the delete_messages() method

prisma girder
#

my bot is giving a error message about this after it work fine all day with out this

hushed galleon
#

the error would suggest you've passed None as the colour= argument

prisma girder
#

yes i have and it wasnt a problem until now

slate swan
prisma girder
hushed galleon
hushed galleon
hushed galleon
#

yea, entirely client-side

slate swan
#

gotcha

prisma girder
hushed galleon
prisma girder
#

yeah

hushed galleon
#

remove it and it'll be fixed

prisma girder
#

the whole thing

pulsar kettle
hushed galleon
prisma girder
#

like none or the whol color = none

hushed galleon
#

just the color=None

hushed galleon
#

i.e. ```py
await interaction.response.defer()

do whatever long task here (webhook takes 15 minutes to expire)

await interaction.followup.send(...)```

crimson mauve
#
Embed = discord.Embed(title=f"{User} has left the server...",
                               description="Bye dude")
Embed.set_image(url="www.weeb.png")
Embed.set_thumbnail(url="www.brokenlink.png")
await .send(embed=Embed)
slate swan
#

Hey whenever I or anyone else sends a message in my discord i get this message in the terminal. Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/discord/client.py", line 409, in _run_event await coro(*args, **kwargs) File "/root/bot/akro.py", line 79, in on_message await bot.process_commands(message) NameError: name 'bot' is not defined

#

any fixes

fading marlin
#

define bot...? gonna need the full code ๐Ÿคท

slate swan
#

fixed it i put bot instead of client

clear elm
#
async def on_member_join(member):
  guild = client.get_guild(1058181103132868619)
  channel = client.get_channel(1058184521587105853)
  embed=discord.Embed(title=f'Welcome To {guild.name}', description=f'Hello, {user.mention}.')
  
  await channel.send(embed=embed)```

im trying to make a welcome event  so when someone joins the server this come up. it's not working though, there's nothing in the terminal and no problems so im not sure whats wrong. all intents are on
clear elm
#

its not a command

slate swan
#

anyone know why whenever i run this command @client.command() async def create(ctx, channel_name: str): guild = ctx.guild existing_channel = discord.utils.get(guild.channels, name=channel_name) if not existing_channel: await guild.create_text_channel(channel_name) await ctx.send(f'Created new channel: {channel_name}') else: await ctx.send(f'Channel {channel_name} already exists') it creates 2 channels?

slate swan
clear elm
slate swan
#

in dms right?

clear elm
#

no, in the server

slate swan
#

hm

hushed galleon
#

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

hushed galleon
clear elm
slate swan
hushed galleon
slate swan
#

nice arrow

hushed galleon
#

ok maybe a bit of a confusing arrow but i mean writing the same intents=intents inside the Bot constructor

clear elm
#

ohhh

#

ok ty

#

client = commands.Bot(command_prefix = "k!", intents.members=True) like this?

hushed galleon
clear elm
#

oh

hushed galleon
#

also discord_slash is a pretty outdated library, discord.py v2.0+ already has native support for slash commands

clear elm
#

oops my bad

#

ok

#

i havent been coding a lot, i havent since like last year april ish

hushed galleon
#

iirc support for dpy 1.7 is going to die pretty soon because the v6 gateway is going to be removed

clear elm
#

ok, ty for letting me know

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.

civic fractal
#

delete lines 14 and 16 altogether

slate swan
hushed galleon
#

you're not meant to use process_commands() in a listener

clear elm
#

omg thank you so much, it finally works

hushed galleon
#

its the same thing described in the FAQ entry you linked earlier

slate swan
#

thank you.

#

i forgot the other option to replace listener with you know what it is?

hushed galleon
#

the .event decorator?

slate swan
#

yes thank you.

ionic garden
#

do i have to manually sync the command tree?

fading marlin
#

you should, yes

lethal creek
#

Could someone explain to me the difference between using command.commands() and bot.tree.commands()? I'm looking at the documentation and it says they should be equivalent, but when I use command.commands() none of my commands work.

I'd like to understand what exactly is happening. I think the root in there is the bot object that I declare? Would it make a difference if instead of something like :

bot = commands.Bot(blah blah blah)

I would have done something like

bot = commands.Client(blah blah blah)?

fading marlin
#

commands.Client doesn't exist either

lethal creek
civic fractal
#

how so?

ionic garden
fading marlin
#

well... you could sync in on_ready or equivalent, but like at that point you're just begging to get ratelimited

fading marlin
ionic garden
fading marlin
#

you sync your commands with discord

#

not the other way around, discord doesn't develop commands

ionic garden
#

i thought they'd detect changes & update or smth

lethal creek
fading marlin
fading marlin
ionic garden
lethal creek
#

Aha, awesome.

#

Thank you very much

fading marlin
ionic garden
#

got it, thanks

fading marlin
#

sure

lethal creek
#

Unfortunately, I have more silly questions.

I'm trying to replace some repetitive code in my commands with a decorator. I only want certain commands to work in certain channels. Right now I just have a basic check that I outsourced to a helper file in a function that returns a boolean and if it's False, send an error message.

I just don't want to keep calling this function. I found the bot.check() decorator, and I'm passing the function, but it keeps giving me an error. Specifically that a Command object doesn't have an attribute called guild, which tells me something is funky with the interaction being passed.

Any ideas?

fading marlin
#

code? error?

lethal creek
#

Error:

sick birch
lethal creek
#

I know that decorators are run from bottom to top and was experimenting with the order, so that is after I swapped them just to see what would happen

fading marlin
#

!d discord.ext.commands.Bot.check

unkempt canyonBOT
#

@check```
A decorator that adds a global check to the bot.

A global check is similar to a [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.

Note

This function can either be a regular function or a coroutine.

Similar to a command [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check"), this takes a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and can only raise exceptions inherited from [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").

Example...
fading marlin
#

use @commands.check instead

civic fractal
#

it should be ```py
def correct_channel(ctx):
right_channel_name = "testingbot"
channel = discord.utils.get(ctx.guild.channels, name=right_channel_name)
right_channel_id = channel.id
current_channel_id = ctx.channel_id
if current_channel_id != right_channel_id:
return False
return True

@bot.tree.command(name="signup", description="Register the user into the database.")
@commands.check(correct_channel)
async def signup(...):
...```

#

flipped the decorator order and used commands.check instead of bot.check

fading marlin
#

hmm, still not quite

#

@app_commands.check, I hadn't notice the tree.command deco

sick birch
#

@lethal creek FYI your entire function can be shortened down to

def correct_channel(ctx):
  return ctx.channel.name == "testingbot"
#

I think you might be overcomplicating a bit ๐Ÿ˜›

lethal creek
fading marlin
#

you gotta import it from discord

sick birch
fading marlin
#

or use the full namespace discord.app_commands.check

lethal creek
civic fractal
#

isn't there an existing way in the library to restrict the channel?

sick birch
civic fractal
#

can't you pass it to bot.tree.command?

civic fractal
#

nvm

lethal creek
sick birch
fading marlin
#

๐Ÿ˜”

lethal creek
#

So then if I want to use check() with slash commands I have to use app_commands?

fading marlin
#

you were right in searching the docs first though!

fading marlin
#

the commands framework and app_commands rarely interact with each other

lethal creek
#

I think I got it to work... except not in the way I expected.

crimson mauve
#

that's the philosophy of the people that run Discord.py, you better already know everything because the docs are just note and you are dumb for knowing less than them.

lethal creek
#

check() will only accept a function that returns a bool, correct? So if it evaluates false, the command doesn't run, which results in an error?

lethal creek
fading marlin
civic fractal
crimson mauve
#

Good luck, if you are anything like me you just start learning how big the dumb pile really is.

civic fractal
#

so py return None or py return [] will also prevent the command from running

#

but yeah you should just return true or false

sick birch
#

Just to be explicit I would recommend return True/False

#

"Explicit is better than implicit"

fading marlin
#

type checkers will shout at you if you don't ducky_australia

sick birch
#

Yeah. Recently got pyright installed for my Emacs configuration and man it will not shut up no matter what I do

#

I've gotta figure out how to turn off strict mode

fading marlin
#

the only reason why I have it set it to strict is because it makes me feel smart ducky_sphere

primal token
#

Real smart people dont use type checkers

clear elm
#
from discord.ext import commands

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

client = discord.Client()

client = commands.Bot(command_prefix = "!", intents=intents) 
client.remove_command('help')

@client.event
async def on_member_join(member):
  guild = client.get_guild(1023746108830257173)
  channel = client.get_channel(1023746108830257177)
  await channel.send(f'{member.mention}', delete_after=5)

@client.event
async def on_member_join(member):
  guild = client.get_guild(1023746108830257173)
  channel = client.get_channel(1026071401825841233)
  await channel.send(f'{member.mention}', delete_after=5)

client.run("") ```

im tryna make a bot where it pings someone 5 minutes after they join in 2 different channels. everything works except when someone joins, it only pings them in one channel  and not both, i was wondering if someone could help me please (im not doing the 5 minutes thing yet) btw thats my whole code
naive briar
#

.event overrides the old event with the new one

#

Also why are you trying to create client 3 times

civic fractal
#

why not just do py @client.event async def on_member_join(member): channel1 = client.get_channel(1023746108830257177) channel2 = client.get_channel(1026071401825841233) await channel1.send(f'{member.mention}', delete_after=5) await channel2.send(f'{member.mention}', delete_after=5)

#

I removed the guild variable because you weren't using it

civic fractal
clear elm
#

yeah idk

#

lol

clear elm
#

how would i make it send it after 5 minutes?

chilly dove
#

use asyncio.sleep

clear elm
#

ok ty

leaden dagger
#

await asyncio.sleep(30)
bot.loop.create_task(on_ready())

for example here i set 30 seconds and its in loop now. Is there any harm in having too little or too much value for it?

leaden dagger
naive briar
#

Show your full code

#

Wait, you're just rate limited yert

leaden dagger
supple ridge
pulsar bridge
#

I've got a friend starting out with coding bots in python... but there's something wrong with his libraries. I'm unsure on what cause this didn't happen to me when I started out (or its been so long that I've forgotten?)

Traceback (most recent call last):
  File "C:\Users\main\Downloads\AAAAAAA\AAAAA.py", line 2, in <module>
    import discord
  File "C:\Users\main\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\__init__.py", line 23, in <module>
    from .client import *
  File "C:\Users\main\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 46, in <module>
    from .ui import print_banner, start_logging
  File "C:\Users\main\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\__init__.py", line 12, in <module>
    from .view import *
  File "C:\Users\main\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 36, in <module>
    from ..components import (
ImportError: cannot import name 'Component' from 'discord.components' (C:\Users\gibbs\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\components\__init__.py)

Thats the error message

slate swan
#

what libraries are you using?

pulsar bridge
# slate swan what libraries are you using?
aiohttp==3.8.3
aiosignal==1.3.1
async-timeout==4.0.2
attrs==22.2.0
charset-normalizer==2.1.1
discord==2.1.0
discord.py==2.1.0
frozenlist==1.3.3
idna==3.4
multidict==6.0.4
yarl==1.8.2
#

Those are his installed packages

supple ridge
pulsar bridge
# slate swan remove the discord library
  File "C:\Users\main\Downloads\AAAAAAA\AAAAA.py", line 3, in <module>
    import discord.net
ModuleNotFoundError: No module named 'discord.net'

Defaulting to user installation because normal site-packages is not writeable
ERROR: Could not find a version that satisfies the requirement discord.net (from versions: none)
ERROR: No matching distribution found for discord.net
green star
#
import discord
from discord.ext import commands

client = commands.Bot(command_prefix='/', intents=discord.Intents.all())

@client.event()
async def on_ready():
    print('we have logged in!')



client.run('TOKEN')```

why is this not working?
pulsar bridge
#

whats the error?

green star
civic fractal
#

remove the parentheses

pulsar bridge
#

remove () from client.event

civic fractal
#
@client.event
async def on_ready():```
mental hollow
#

how would you remove a file from a message?

#

^ editing the message + passing file=None causes AttributeError: 'NoneType' object has no attribute 'fp'

sick birch
#

Wrong language ๐Ÿ‘€

slate swan
#

wrong import syntax too๐Ÿ—ฟ

#

oh no wait c# is Microsoft java, its correct

civic fractal
green star
slate swan
#

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

sick birch
pulsar bridge
slate swan
#

enable from portal

slate swan
pulsar bridge
#

Aight, next library

#

from dotenv import load_dotenv ModuleNotFoundError: No module named 'dotenv'

slate swan
#

pip install python-dotenv

upbeat otter
pulsar bridge
#

maybe he's mispelling it?
I'm on a call right now with him ๐Ÿ’€

supple ridge
#

install it

supple ridge
mental hollow
civic fractal
#

well a file is an attachment though

slate swan
#

when editing a message it's an attachment, not a file

civic fractal
#

and you cannot pass files to an .edit call

slate swan
#

it should be a common sense that a file is a stored object, while attachment is a part of a message

mental hollow
civic fractal
#

oh you're using a different library

#

idk you can try message.edit(files=[])

#

I would recommend trying that with pycord regardless

slate swan
#

its same for either

#

pycord is nothing but a fork

#

and same Endpoints are being used there

civic fractal
#

I know but clearly the edit method is different

#

discord.py does not support a file or files argument, only attachments

#

whereas pycord accepts the former two

#

I think pycord forked from dpy 1.7.3 where those arguments may have been defined

slate swan
# civic fractal I know but clearly the edit method is different

might seem like that but no its same

property edit
This function is a coroutine.

Edits the original interaction response message.

This is a lower level interface to InteractionMessage.edit() in case you do not want to fetch the message and save an HTTP request.

#

its just message.edit in background

civic fractal
#

what

slate swan
#

file is for sending
attachment is for editing

#

all libraries have both

civic fractal
#

I said that the methods are different

#

you seem to disagree

#

right?

slate swan
#

i said that context.edit is nothing but a shortcut to message.edit

civic fractal
#

I never doubted that

#

I guess we don't disagree then

slate swan
#

!d discord.abc.Messageable.send

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

Sends a message to the destination with the content given.

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

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

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
civic fractal
slate swan
#

edit, yeah

#

because it shouldn't be there

pliant gulch
civic fractal
#

since when are we talking about the sendmethod lol

civic fractal
slate swan
#

another reason why pycord is trash

#

i misread it then

sick birch
#

i'll add it to the ever growing list

pliant gulch
#

Is there a reason pycord has file(s) in edit

civic fractal
pliant gulch
slate swan
pliant gulch
#

Using the official API there is a file[n] key

#

And an attachments key

slate swan
#

!d discord.InteractionMessage.edit

unkempt canyonBOT
#

await edit(*, 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 message.
pliant gulch
#

I see, both use multipart form data

#

But yes the offical API has a file[n] parameter

slate swan
#

ig discord.py did that to maintain consistency between Message.edit and InteractionMessage.edit

pliant gulch
#

And an attachments parameter

charred radish
#

uhh whats the color code for invisible embed?

sick birch
unkempt canyonBOT
#
No way, Josรฉ.

No documentation found for the requested symbol.

charred radish
#

or the color which matches discord's bg color

sick birch
#

!d discord.Colour.dark_theme

unkempt canyonBOT
#

classmethod dark_theme()```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") with a value of `0x36393F`. This will appear transparent on Discordโ€™s dark theme.

New in version 1.5.
sick birch
#

i hate the british spelling

uneven jackal
#

do U :p

sick birch
#

At least when the documentation only works for one version, haha

uneven jackal
#

Oh no! You got bit by the Rust bug too eh. (I'm trying really hard to ignore Rust and Go and focus one lang lol (I peeped your prof)

sick birch
uneven jackal
#

Oh see why'd you hafta go and say something exciting like that when I'M ON A DIET! =P

#

d! Pandas

supple ridge
#

regex returns a list right?

candid geyser
uneven jackal
#

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

shrewd apex
supple ridge
subtle jolt
#

getting this error when importing the discord-py-interactions file addon thingy ma bob

Traceback (most recent call last):
  File "c:\Users\Lenovo User\Desktop\LifeAsPy\Hypixel Api\LobbyChat\testing.py", line 3, in <module>
    from interactions.ext.files import command_send
  File "C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\interactions\ext\files\__init__.py", line 1, in <module>
    from .files import *
  File "C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\interactions\ext\files\files.py", line 15, in <module>
    from interactions import (
ImportError: cannot import name 'LibraryException' from 'interactions' (C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\interactions\__init__.py)
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x00000217889E1090>```

even the example is giving that error
naive briar
slate swan
#
async def defaulttest(self, interaction: discord.Interaction, create:str=None) -> None:

The same way I made that create:str=None parameter, is there a way to make it a selectable option but you dont have to type anything into it?

naive briar
unkempt canyonBOT
#

examples/app_commands/transformers.py lines 80 to 87

# In order to support choices, the library has a few ways of doing this.
# The first one is using a typing.Literal for basic choices.

# On Discord, this will show up as two choices, Buy and Sell.
# In the code, you will receive either 'Buy' or 'Sell' as a string.
@client.tree.command()
@app_commands.describe(action='The action to do in the shop', item='The target item')
async def shop(interaction: discord.Interaction, action: Literal['Buy', 'Sell'], item: str):```
naive briar
#

Literal is from typing module btw

subtle jolt
unkempt canyonBOT
#

examples/app_commands/basic.py lines 47 to 54

@client.tree.command()
@app_commands.describe(
    first_value='The first value you want to add something to',
    second_value='The value you want to add to the first value',
)
async def add(interaction: discord.Interaction, first_value: int, second_value: int):
    """Adds two numbers together."""
    await interaction.response.send_message(f'{first_value} + {second_value} = {first_value + second_value}')```
slate swan
pulsar kettle
#

Tring to code a purge command, however it only deletes int-1 of whatever value I put, doesn't send the embed and gets this error in the code: discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10008): Unknown Message
Any help would be great

@bot.tree.command(name='purge', description='Deletes a specified number of messages from a channel')
@has_permissions(administrator=True)
async def purge(interaction: discord.Interaction, limit: int):
    embed = discord.Embed(title=(f'Purged {limit} messages'), color=0xf6ff00)
    await interaction.response.defer()
    await interaction.channel.purge(limit=limit)
    await interaction.followup.send(embed=embed)```
unkempt canyonBOT
#

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

A full traceback could look like:

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

If the traceback is long, use our pastebin.

supple ridge
solid orbit
#

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

solid orbit
#

how do i let my bot go online?

#

yes but what is the code to get the bot online?

#

it says things about intents

#

here

#

did it

#

but still not working (this is my first bot btw)

#

yes

#

do you have like a standard code to get the bot online?

naive briar
supple ridge
solid orbit
#

now it says:

supple ridge
#

from discord.ext import commands

supple ridge
solid orbit
#

i import: import discord, from discord.ext import commands

#

but now it says:

supple ridge
#

LMFAO

#

DELETE BRO

#

@solid orbit DELETE IT

solid orbit
#

i have reset the token

#

chill Xd

supple ridge
#

enclose it in ""

#

@naive briar regex pro pithink pithink

solid orbit
#

it still does not work

#

don't you just have a standard code template that is used to get a bot online?

#

i can't this will be like 20 screenshots

#

its so long

naive briar
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.

solid orbit
#

this is not even all

#

i did

#

oh oops

#

that was an old screenshot

#

i already tried

#

i tried like 6 times already

naive briar
#

Reset your bot token also

solid orbit
#

i did

supple ridge
#

how can i detect reactions?

crimson mauve
# solid orbit i already tried

It's because you need to have your token as a string. Without it between "" the computer thinks you are trying to call a variable.