#discord-bots

1 messages · Page 1120 of 1

brazen raft
#

Sure, that depends on where you get your guild object from

loud junco
#

ye...

real grail
brazen raft
#

You need to get a specific guild then

#

From what specific guild do you want to get its members' IDs

#

And what do you need this for?

#

Some system?

slate swan
#

its pointing at [0] btw

#

oh

real grail
# brazen raft Some system?

Economy system. The bot must, at startup, iterate over all server members (id) and check the value in the database. If the value is None - the bot performs a specific action

slate swan
#

main.py:17 RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension(extension)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

slate swan
slate swan
#

pithink @dusky pine check prs

slate swan
real grail
modern rune
#

Uhm i had a look at discord.py but the docs kinda suck. Isn’t there something in python with a better tutorial (like discord.js)?

slate swan
brazen raft
slate swan
loud junco
#

u know what is indent right?

brazen raft
#

How did you mess up the indentation

dusky pine
loud junco
dusky pine
#

i'll review later

slate swan
loud junco
#

sure

slate swan
loud junco
#
this
  is
    indent
slate swan
#

!indent

unkempt canyonBOT
#

Indentation

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

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

Example

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

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

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

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

slate swan
#

dk why there's no command with the full name 💀

loud junco
#

?

slate swan
# loud junco ?

the command name is indent but as you can see in the title it should actually me indentation

lilac peak
#
    elif value == "Ban" or "B":
        embed = discord.Embed(title="🔨 Ban", description="Służy do banowania użytkowników.", color=0xffffff)
        embed.add_field(name="📕 Użycie:", value='`.ban <@użytkownik> <powód>`')
        embed.add_field(name="📖 Przykład użycia:", value='`.ban @człowiek spam`')
        embed.add_field(name="🗂 Kategoria:", value="Moderacja")
        embed.add_field(name="🚨 Potrzebna permisje:", value ="Banowanie członków")
        embed.add_field(name="💾 Dodatkowe informacje:", value = "Brak.")
        embed.add_field(name="🔠 Inne sposoby wpisania komendy:", value = "`.b`")
        await ctx.send(embed=embed)

    elif value == "Ogłoś" or "Oglos" or "O":
        embed = discord.Embed(title="📢 Ogłoś", description="Służy do wysyłania wiadomości na #📢-ogłoszenia.", color=0xffffff)
        embed.add_field(name="📕 Użycie:", value='`.ogłoś <ogłoszenie>`')
        embed.add_field(name="📖 Przykład użycia:", value='`.ogłoś coś tam ważnego`')
        embed.add_field(name="🗂 Kategoria:", value="Ogłoszenia")
        embed.add_field(name="🚨 Potrzebna permisje:", value ="Zarządzanie kanałami")
        embed.add_field(name="💾 Dodatkowe informacje:", value = "Możesz pisać jakiej chcesz długości wiadomości póki nie będziesz miał/a limitu od discorda.")
        embed.add_field(name="🔠 Inne sposoby wpisania komendy:", value = "`.oglos`, `.o`")
        await ctx.send(embed=embed)

when i write .pomoc ogłoś bot send to me what it should be .pomoc ban
i don't have error

slate swan
#

seems right

#

but you can't use await outside an async function

brazen raft
slate swan
#

consider using setup_hook 👀 or make a coroutine which loads the extensions and then uses bot.start

#

why did i write embed, idk

slate swan
brazen raft
brazen raft
#

Use dicsord.ext.tasks.loop if you are using discord.py

slate swan
#
@tasks.loop(seconds=15)
async def status_roles(ctx):
    guild = client.get_guild(921366728016011324)
    fluf = await bot.fetch_user('716707479005823036')
    for member in guild.members:
        if member.activities and 'discord=i' in member.activities[0].name.lower():
            await member.add_role(discord.Object(id=921720262217568268))
            await DMChannel.send(fluf, f'gave supporter role to {member}')
        elif member.activities and 'dis=oofi' not in member.activities[0].name.lower():
            await member.remove_role(discord.Object(id=921720262217568268))
            await DMChannel.send(fluf, f'removed supporter role from {member}')
lilac peak
#
    elif value == "Ban" or "B":
        embed = discord.Embed(title="🔨 Ban", description="Służy do banowania użytkowników.", color=0xffffff)
        embed.add_field(name="📕 Użycie:", value='`.ban <@użytkownik> <powód>`')
        embed.add_field(name="📖 Przykład użycia:", value='`.ban @człowiek spam`')
        embed.add_field(name="🗂 Kategoria:", value="Moderacja")
        embed.add_field(name="🚨 Potrzebna permisje:", value ="Banowanie członków")
        embed.add_field(name="💾 Dodatkowe informacje:", value = "Brak.")
        embed.add_field(name="🔠 Inne sposoby wpisania komendy:", value = "`.b`")
        await ctx.send(embed=embed)

    elif value == "Ogłoś" or "Oglos" or "O":
        embed = discord.Embed(title="📢 Ogłoś", description="Służy do wysyłania wiadomości na #📢-ogłoszenia.", color=0xffffff)
        embed.add_field(name="📕 Użycie:", value='`.ogłoś <ogłoszenie>`')
        embed.add_field(name="📖 Przykład użycia:", value='`.ogłoś coś tam ważnego`')
        embed.add_field(name="🗂 Kategoria:", value="Ogłoszenia")
        embed.add_field(name="🚨 Potrzebna permisje:", value ="Zarządzanie kanałami")
        embed.add_field(name="💾 Dodatkowe informacje:", value = "Możesz pisać jakiej chcesz długości wiadomości póki nie będziesz miał/a limitu od discorda.")
        embed.add_field(name="🔠 Inne sposoby wpisania komendy:", value = "`.oglos`, `.o`")
        await ctx.send(embed=embed)

when i write .pomoc ogłoś bot send to me what it should be .pomoc ban
i don't have error

slate swan
#

!d discord.ext.tasks.loop use a task, use get_channel to get the channel, and use .send() method

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
sick panther
#

Hi, hi, just a simple question;

I'm working on my bot, and came to the idea to make an anti-raid prevention. So, first of all it is checking if the message has more then 1 character, and if it doesn't it does get deleted. But the problem here is, that It does also delete it, if someone only sends a picture as it doesn't contain any message in it. Now I'm just asking, how can I check if there's an attachment? I'm honestly for some reason not finding it out;

      if len(msg.content) < 2:
        if msg.content # I don't know for what I should check here
          await msg.delete()
          return await msg.channel.send(f"Hey {msg.author.mention} Your message can not contain less then 2 characters. This is an anti-raid prevention to keep the server clean.", delete_after=5.0)
lilac peak
#

!d if

unkempt canyonBOT
#
if

8.1. The if statement

The if statement is used for conditional execution:


if_stmt ::=  "if" assignment_expression ":" suite
             ("elif" assignment_expression ":" suite)*
             ["else" ":" suite]
``` It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true (see section [Boolean operations](https://docs.python.org/3/reference/expressions.html#booleans) for the definition of true and false); then that suite is executed (and no other part of the [`if`](https://docs.python.org/3/reference/compound_stmts.html#if) statement is executed or evaluated). If all expressions are false, the suite of the [`else`](https://docs.python.org/3/reference/compound_stmts.html#else) clause, if present, is executed.
slate swan
brazen raft
sick panther
brazen raft
#

It's a fork so maybe it's in the same package

#

I haven't checked

brazen raft
unkempt canyonBOT
sick panther
#

Oh, damn. I didn't thought it's that simple, thanks lmao

brazen raft
#

👍

slate swan
#

no error

#

no role given,no message

slate swan
brazen raft
#

If there is no error then the user was fetched or this line wasn't run

slate swan
brazen raft
#

And yeah, tasks.loop loops need to be started

slate swan
#
@loop(...)
async def foo(): ...

foo.start()
``` since its a loop working with requests consider doing it after wait_until_ready
#

ooooooooooooooooooooooohhhhhhhhhhhhhhhhhh

#

why tf

vocal snow
#

You can do this

#

I believe in you

slate swan
#

!d discord.ext.tasks.Loop.start

unkempt canyonBOT
slate swan
#

did it 😏

brazen raft
#

Ah

#

Really weird

slate swan
#

Loop is the object which @loop constructs

brazen raft
#

Makes sense I guess

slate swan
#

👀 its same for commands

@commands.command()
async def foo(ctx):
  ...
``` `foo` here will become a commands.Command object
brazen raft
#

Yeah they do do it like that

slate swan
#

help

shrewd apex
#

did u fetch the guild?

#

!d discord.Guild.members

unkempt canyonBOT
slate swan
shrewd apex
#

then perhaps the guild I'd not there in cache

slate swan
#

hoooooowwwwwwwwwwwwww do i put it in cache]

paper sluice
shrewd apex
#

guild = bot.get_guild(921366728016011324) or await bot.fetch_guild(id)

#

id here is the number please don't copy paste

slate swan
#

oh

slate swan
shrewd apex
#

oops didn't read

dusky pine
paper sluice
loud junco
#

LOL nitro

#

but 😭 looks better

slate swan
#

still no error no message no role

loud junco
#

hmm

slate swan
loud junco
slate swan
#
async def status_roles():
    guild = await bot.fetch_guild(921366728016011324)
    fluf = await bot.fetch_user(716707479005823036)
    for member in guild.members:
        if member.activities and 'discord=loofi' in member.activities[0].name.lower():
            await member.add_role(discord.Object(id=921720262217568268))
            await DMChannel.send(fluf, f'gave supporter role to {member}')
        elif member.activities and 'discordloofi' not in member.activities[0].name.lower():
            await member.remove_role(discord.Object(id=921720262217568268))
            await DMChannel.send(fluf, f'removed supporter role from {member}')
              
    
status_roles.start()
slate swan
#

start that task after the bot is ready

#

oh

#

after bot.run?

#
@tasks.loop(...)
async def task(): ...

async def start_task():
   await bot.wait_until_ready()
   task.start()

async def on_ready():
    await start_task()
#

something like this

#

wwwwwww

#

i did it

shrewd apex
#

why not just make a task.before_loop

#

and in that wait until ready

slate swan
#
@tasks.loop(seconds=10)
async def task():
    guild = await bot.fetch_guild(921366728016011324)
    fluf = await bot.fetch_user(716707479005823036)
    for member in guild.members:
        if member.activities and 'discordoofi' in member.activities[0].name.lower():
            await member.add_role(discord.Object(id=921720262217568268))
            await DMChannel.send(fluf, f'gave supporter role to {member}')
        elif member.activities and 'discoofi' not in member.activities[0].name.lower():
            await member.remove_role(discord.Object(id=921720262217568268))
            await DMChannel.send(fluf, f'removed supporter role from {member}')
async def start_task():
   await bot.wait_until_ready()
   task.start()

async def on_ready():
    await start_task()
#

help

#

please

brazen raft
#

Or does on_ready fire after the bot is ready

#

In that case doing await bot.wait_until_ready() is unnecessary

maiden fable
#

!d discord.on_ready

unkempt canyonBOT
#

discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.guilds "discord.Client.guilds") and co. are filled up.

Warning

This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
maiden fable
#

Hm, it's triggered when the not connects to the ws

shrewd apex
#
@tasks.loop(seconds=10)
async def task():
    guild = await bot.fetch_guild(921366728016011324)
    fluf = await bot.fetch_user(716707479005823036)
    for member in guild.members:
        if member.activities and 'discordoofi' in member.activities[0].name.lower():
            await member.add_role(discord.Object(id=921720262217568268))
            await DMChannel.send(fluf, f'gave supporter role to {member}')
        elif member.activities and 'discoofi' not in member.activities[0].name.lower():
            await member.remove_role(discord.Object(id=921720262217568268))
            await DMChannel.send(fluf, f'removed supporter role from {member}')

@task.before_loop():
async def pre():
    await bot.wait_until_ready()

async def on_ready():
    task.start()
brazen raft
shrewd apex
#

just add a print statement and see if the task is starting

brazen raft
#

Also fetching the guild and the user every ten seconds spends an unnecessary amount of time

slate swan
#

@task.before_loop()
TypeError: before_loop() missing 1 required positional argument: 'coro'

paper sluice
#

dont call it

brazen raft
#

Just remove the whole pre function definition thing and put await bot.wait_until_ready() in the function of the loop itself

#

I think that would be best

slate swan
#

wdym

#

its still giving this error @task.before_loop()
TypeError: before_loop() missing 1 required positional argument: 'coro'

heady sluice
#

on_message has message, not ctx

#

and why are you even getting a channel

#

also, use @bot.listen() instead of @bot.event just here

paper sluice
#

stop calling before_loop 😢

heady sluice
#

remove the ()

slate swan
#

will it work now[]

honest shoal
#

how much options can I have in an autocomplete?

shrewd apex
slate swan
shrewd apex
#

🤦

#

in the main task

slate swan
#

oh

slate swan
heady sluice
#

we assume it doesn't work

slate swan
#
guild = bot.fetch_guild(921366728016011324)
fluf = bot.fetch_user(716707479005823036)
@tasks.loop(seconds=10)
async def task():
    print("hello")
    for member in guild.members:
        if member.activities and 'discordoofi' in member.activities[0].name.lower():
            await member.add_role(discord.Object(id=921720262217568268))
            await DMChannel.send(fluf, f'gave supporter role to {member}')
        elif member.activities and 'discoofi' not in member.activities[0].name.lower():
            await member.remove_role(discord.Object(id=921720262217568268))
            await DMChannel.send(fluf, f'removed supporter role from {member}')
async def on_ready():
    await bot.wait_until_ready()
    task.start()
#

hekp

heady sluice
#

don't start it inside on_ready

slate swan
#

where do i start

#

it

heady sluice
#

above bot.run

slate swan
#

okay

heady sluice
#

and you add a wait_until_ready in the task

#

await bot.wait_until_ready()

slate swan
#

it did print hello

#

but]

heady sluice
#

error

slate swan
#
    await self.coro(*args, **kwargs)
  File "main.py", line 62, in task
    for member in guild.members:
AttributeError: 'coroutine' object has no attribute 'members'
heady sluice
#

do you have a function called guild

#

oh wait I see

slate swan
#

guild = bot.fetch_guild(921366728016011324)

heady sluice
#

you have to use await

slate swan
#

await where?

heady sluice
#

await bot.fetch_guild

slate swan
#

ooh

heady sluice
#

inside a coroutine

#

but then you won't even be in the right scope

#

hard

slate swan
#

didnt get any error

#

it keeps printing hello

#

but no messsgae in dm

#

and no roles

heady sluice
#

none of your if statements are true

slate swan
#

but my status

#

is ture]]\

heady sluice
#

you don't have one

slate swan
#

oh

#

nnow?

heady sluice
#

I don't see it

slate swan
#

whaaaaaaa

#

i can see it

shrewd apex
#

i can't either

wanton cipher
#

How can I avoid the webhook erroring like so after a certain amount of time? disnake.errors.HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token Context: I have a slash command and I edit the original message every so often, and after a while, it errors like so

slate swan
#

noww?
\

#

Im making a discord bout with slash-commands and they work and all but I am making one that sends an embed so I make the embed perfect and then I do ```py
await ctx.send(embed=embed)

#

and the error is "unexpected keyword argument embed"

heady sluice
slate swan
# heady sluice yes
@tasks.loop(seconds=15)
async def task():
    guild = await bot.fetch_guild(921366728016011324)
    fluf = await bot.fetch_user(716707479005823036)
    print("Function done")
    for member in guild.members:
        if member.activities and 'discoloofi' in member.activities[0].name.lower():
            await member.add_role(discord.Object(id=921720262217568268))
            await DMChannel.send(fluf, f'gave supporter role to {member}')
        elif member.activities and 'discorloofi' not in member.activities[0].name.lower():
            await member.remove_role(discord.Object(id=921720262217568268))
            await DMChannel.send(fluf, f'removed supporter role from {member}')

keep_alive()
bot.wait_until_ready()
task.start()
bot.run(token)
#

still no role

slate swan
#
@tasks.loop(seconds=15)
async def task():
    guild = await bot.fetch_guild(921366728016011324)
    fluf = await bot.fetch_user(716707479005823036)
    print("Function done")
    for member in guild.members:
        print('h')
        if member.activities and 'discordfi' in member.activities[0].name.lower():
            await member.add_role(discord.Object(id=921720262217568268))
            await DMChannel.send(fluf, f'gave supporter role to {member}')
        elif member.activities and 'discorloofi' not in member.activities[0].name.lower():
            await member.remove_role(discord.Object(id=921720262217568268))
            await DMChannel.send(fluf, f'removed supporter role from {member}')
#

!d discord.Client.wait_until_ready ensures that the cache is ready

unkempt canyonBOT
#

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

Waits until the client’s internal cache is all ready.

Warning

Calling this inside [`setup_hook()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.setup_hook "discord.Client.setup_hook") can lead to a deadlock.
slate swan
#

its not printing h but its printing function done\

slate swan
#

!intents read this and see the codeblock

unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

slate swan
#

How would I go around implementing a queue for commands so the command happens after the other has finished

slate swan
#

show your commands.Bot variable

#

bot = commands.Bot(command_prefix="-", owner_id=716707479005823036, intents=intents)

slate swan
#

and the intents

slate swan
# slate swan and the intents
from discord import Intents
from discord import Embed
os.system('clear')

intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="-", owner_id=716707479005823036, intents=intents)
#

seems good, still no hs?

#

and did you use the method i asked you to?

#

not printing h

heady sluice
#

it's not good for his use

#

he checks activities

slate swan
#

how do i do it then

heady sluice
#

you need presence intents, you could just use Intents.all()

#

and enable presence intents in the dev portal

slate swan
#

it should still print h tho

#

they are enabled

heady sluice
#

yeah it should print h

mortal mango
#

if youre trying to share the full code snippet, please remove the guild invite url from it and try again. our filter doesn't like invite urls.

robust fulcrum
#

Guys is it possible to make a afk command without database?

slate swan
#
@tasks.loop(seconds=15)
async def task():
    guild = await bot.fetch_guild(921366728016011324)
    fluf = await bot.fetch_user(716707479005823036)
    print("Function done")
    for member in guild.members:
        print('h')
        if member.activities and 'discord=oofi' in member.activities[0].name.lower():
            await member.add_role(discord.Object(id=921720262217568268))
            await DMChannel.send(fluf, f'gave supporter role to {member}')
        elif member.activities and 'discor=floofi' not in member.activities[0].name.lower():
            await member.remove_role(discord.Object(id=921720262217568268))
            await DMChannel.send(fluf, f'removed supporter role from {member}')

keep_alive()
bot.wait_until_ready()
task.start()
bot.run(token)
#

help

#

please

slate swan
#

someone

#

please

slate swan
#

and it takes time to go through all of them

#

no that should not be the case

#

it should print h when checking every member

#

and looping on 400 elements shouldn't take too much time either

#

hm

shrewd apex
#

what's the formatting for having thats ascii box in an embed which works on phone as well like 3*` followed by __

slate swan
#

or members

wanton cipher
#

How can I avoid the webhook erroring like so after a certain amount of time? disnake.errors.HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token Context: I have a slash command and I edit the original message every so often, and after a while, it errors like so. I am not too sure if it's the command interaction timing out or something or whatever, but I'm so so so lost

sick birch
#

You can only edit the original message once I believe

wanton cipher
#

I was able to edit it multiple times

#

but maybe there is a limit...

#

never thought of that

sick birch
#

Are you using followup?

#

That’s what you should use after the first time

wanton cipher
#

here, this might help ```py
async def slash_command(self, inter: disnake.CommandInteraction):
await inter.response.defer(ephemeral=True)

    while 1:
        await inter.edit_original_message(...)
swift pumice
#
async def waifu(ctx):
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get("https://nekos.life/api/v2/img/waifu") as r:
                data = await r.json()
                await ctx.send(data["url"])
    except Exception as e:
        await ctx.send(f'{e}')

``` why isnt this working? it just send in the chat *storage_url*
heady sluice
#

why do you have wait_until_ready there

#
@tasks.loop(seconds=15)
async def task():
    await bot.wait_until_ready()
    guild = await bot.get_guild(921366728016011324)
    fluf = await bot.get_user(716707479005823036)
    print("Function done")
    for member in guild.members:
        print('h')
        if member.activities and 'discord=oofi' in member.activities[0].name.lower():
            await member.add_roles(discord.Object(id=921720262217568268))
            await fluf.send(f'gave supporter role to {member}')
        elif member.activities and 'discor=floofi' not in member.activities[0].name.lower():
            await member.remove_roles(discord.Object(id=921720262217568268))
            await fluf.send(f'removed supporter role from {member}')

keep_alive()
task.start()
bot.run(token)
#

not sure about the discord.Object way there

slate swan
#

nvm

heady sluice
#
  • after being ready you can get items from the cache with get_ instead of fetch_
wanton cipher
#

oh, how come?

slate swan
#

you shouldnt run an infinite loop for edit_original_message

#

and you are probably running out of number of edits

wanton cipher
#

OH, there is a limit

wanton cipher
slate swan
#

Help

slate swan
#

Im making a discord bot that can lookup "Ip Addresses" and Im making it use / commands and use embeds but when I try used embeds it does an error even though its perfect this is the code for the end embed

await ctx.send(embed=em)
shrewd apex
wanton cipher
slate swan
wanton cipher
#

lel

slate swan
#

TypeError: send() got an unexpected keyword argument 'embed'

shrewd apex
# slate swan who knows

idk i used it in the button map Walker with defer and it seems to work even after lot of edits

vocal snow
slate swan
#

cant

slate swan
slate swan
shrewd apex
#

hmm no

slate swan
#

nvm that

shrewd apex
honest shoal
#

how much options can I have in an autocomplete?

shrewd apex
#

if there is callback why make a loop

slate swan
# slate swan

dont use a third party library, v2 supports inbuilt slash commands

#

Im using repl

#

....

#

I cant use v2

#

why is that?

#

I tried

#

please elaborate with reasons

#

and wont work

#

I tried it and it didnt work

honest shoal
# shrewd apex 25

umm, I think there's a way like if user types other options will be searched
how can I use that?

slate swan
#

reason and error

#

It wont work

#

what was the error?

slate swan
#

in repl

#

wtf

shrewd apex
#

discord always allows 25 cap buttons reactions options

honest shoal
slate swan
shrewd apex
# slate swan wtf

i took a look in the help channel then went to clean my eyes with kleenex

shrewd apex
honest shoal
shrewd apex
#

why not make a custom function using fuzzy wuzzy or difflib for that

shrewd apex
honest shoal
shrewd apex
# slate swan pft

bro i mean i know almost 0 to none abt slash commands and that still didn't make sense to me

shrewd apex
honest shoal
#

and what is fuzzy wuzzy

slate swan
shrewd apex
#

🤦

honest shoal
#

wait a min

slate swan
unkempt canyonBOT
slate swan
#

its inbuilt

shrewd apex
#

f difflib is in built

slate swan
#

!d difflib

shrewd apex
#

yeah

unkempt canyonBOT
#

Source code: Lib/difflib.py

This module provides classes and functions for comparing sequences. It can be used for example, for comparing files, and can produce information about file differences in various formats, including HTML and context and unified diffs. For comparing directories and files, see also, the filecmp module.

slate swan
unkempt canyonBOT
slate swan
#

i know what shit is that :)

#

thats what I use

#

I saw

#

thanks

shrewd apex
#

use the 2.0 git link

swift pumice
#

do you guys have any command ideas?(for beginners)

shrewd apex
#

make an anime wrapper

honest shoal
#

won't it work for me?

shrewd apex
shrewd apex
swift pumice
shrewd apex
#

ic

honest shoal
#

husbando command then

shrewd apex
#

^

swift pumice
cloud dawn
shrewd apex
sick birch
#

See pydis/botcore for ideas

shrewd apex
#

akg ^

sick birch
#

When we create a new bot we always use that core

slate swan
#
webhook = await message.channel.create_webhook(name=message.author.display_name)
            await webhook.send(content=message.content, avatar_url=member.display_avatar.url)

i have this code to create a webhook and send message, but the bot does not create webhook and i dont get any traceback/error

#

some1 know whats wrong?

sick birch
#

Make sure you have a strong foundational infrastructure before making commands

shrewd apex
#

is there like a good gist or docs on how to do that

cloud dawn
#

But by using [...][:25] you can use a broader suggestions.

sick birch
shrewd apex
#

ic hmm

robust fulcrum
shrewd apex
#

a dictionary

honest shoal
cloud dawn
shrewd apex
#

afk={guildid:{userid:message}}

honest shoal
#

any examples or docs for it?

cloud dawn
shrewd apex
cloud dawn
unkempt canyonBOT
#

@discord.app_commands.autocomplete(**parameters)```
Associates the given parameters with the given autocomplete callback.

Autocomplete is only supported on types that have [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)"), [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)"), or [`float`](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)") values.

[`Checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") are supported, however they must be attached to the autocomplete callback in order to work. Checks attached to the command are ignored when invoking the autocomplete callback.

For more information, see the [`Command.autocomplete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command.autocomplete "discord.app_commands.Command.autocomplete") documentation.

Example:
honest shoal
unkempt canyonBOT
#

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

Creates a webhook for this channel.

Requires [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") permissions.

Changed in version 1.1: Added the `reason` keyword-only parameter.
honest shoal
cloud dawn
#

And max a list of 20 options.

shrewd apex
#

u can use fuzzy wuzzy or difflib to narrow down and then do [:25] in place of fruits list ig not too sure

honest shoal
cloud dawn
#

It will cut the list to max 20 items.

shrewd apex
cloud dawn
shrewd apex
#

so just pass the list of strings?

cloud dawn
shrewd apex
#

ic

#

but then won't the autocomplete only search from those 20?

cloud dawn
# shrewd apex ic

If you want certain items to be on top you'd need to manipulate the list but else it will just be alphabetically.

shrewd apex
#

so he has a list of Pokemon names i assume and since he wants to auto complete then if he just uses first 20 it won't workpithink

shrewd apex
#

he needs to narrow it down to around 20 options and then pass as options right?

shrewd apex
#

yes

cloud dawn
#

!e print(list(range(100))[:25])

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your eval job has completed with return code 0.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
shrewd apex
#

so for the narrowing down i suggested difflib or fuzzy

shrewd apex
cloud dawn
shrewd apex
#

ic

cloud dawn
honest shoal
#

!e py options = ["option 1", "option 2", "option 3", "option 4"] print(options[:3])

unkempt canyonBOT
#

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

['option 1', 'option 2', 'option 3']
shrewd apex
#

so discord sorts that list and then u just pick 20 using [:20]

cloud dawn
#

For really basic stuff yes, you can also apply your own fuzzy on the list if you really want that but from personal experience it's fine.

shrewd apex
#

ic i haven't used slash b4 so wasn't familiar with the procedure

cloud dawn
#

Slash has it's good sides.

#

I use it because it has strict datatypes so you don't have to keep in mind that people are annoying.

still swan
#

why... should i delete it?

sick birch
#

I think the dynamic autocomplete is one of the better features of slash commands, I was able to fetch records from my database and feed it through

honest shoal
#

Is this fine?```py
ok = ["xyz", "zyx", "yxz", ...]

@bot.slash_command()
async def abc(inter: disnake.CommandInteraction, options: str):
...

@options.autocomplete("ok")
async def ok_autocomp(inter: disnake.CommandInteraction, string: str):
string = string.lower()
return [opt for lang[:20] in ok if string in opt.lower()]```

sick birch
cloud dawn
slate swan
#

choices aren't dynamic either afaik

cloud dawn
slate swan
#

Should I make one bot with many functions or should I divide the functions into multiple bots? Don't know if it matters at all

cloud dawn
#

Depends on the "functions".

slate swan
cloud dawn
robust fulcrum
#

Guys is there any cloud database that i am use in my discord bot for prefixes for free
And it can be used on replit

cloud dawn
robust fulcrum
#

But i am a mobile user

slate swan
robust fulcrum
#

Do it matter?

cloud dawn
#

Coding on a phone..?

slate swan
#

what's that excuse lol

cloud dawn
robust fulcrum
still swan
#

@slate swan

slate swan
cloud dawn
robust fulcrum
cloud dawn
robust fulcrum
#

Replit also have it's own db but bad one

slate swan
# still swan <@456226577798135808>

it is not okay since you should be installing it using pip and simply downloading the files will only make it accessible at that specific path where the folder is located

robust fulcrum
#

Do i need to download something

slate swan
robust fulcrum
cloud dawn
#

I'd suggest to save the hassle and use the repl it db

paper sluice
#

coding on phone must be awful

slate swan
#

replit db isnt that good

#

plus it's not async like aiosqlite

#

and you can only have 1gb storage per repl iirc

still swan
#

its okay? or should i delete and reinstall using pip?

slate swan
slate swan
slate swan
still swan
#

its giving me error when i use git+https

slate swan
#

wut gawd

slate swan
still swan
#

oh

still swan
#

thx xd <33

robust fulcrum
still swan
pliant gulch
paper sluice
#

yo andy, how do u quit the terminal when u do :sp | terminal

still swan
#

ty @slate swan <33

slate swan
robust fulcrum
slate swan
slate swan
robust fulcrum
#

Can you guide for it me tommorow pls?

robust fulcrum
#

My bot on 6 server yet

faint dagger
#

ModuleNotFoundError: No module named 'discord.ui' What to do?

robust fulcrum
slate swan
pliant gulch
paper sluice
robust fulcrum
slate swan
#

no

robust fulcrum
#

I also installed

slate swan
#

that's not how 😭

pliant gulch
robust fulcrum
#

And it's working

slate swan
#

...?

#

probably a third party lib

robust fulcrum
#

No

slate swan
#

yes

#

do I look like a clown or what 😔

robust fulcrum
#

I just used it for views

slate swan
#

oh god

robust fulcrum
faint dagger
robust fulcrum
#

Anyway bye good night sweet dream

slate swan
#

smh

robust fulcrum
slate swan
#

imagine lying

#

totally not me

robust fulcrum
#

Pls help if i not sleep my mom will beat me

#

Bye

slate swan
#

lmao bye good night

heady sluice
slate swan
heady sluice
slate swan
faint dagger
#

Cool, I broke the bot.-.

shrewd apex
#

🎉

faint dagger
#

ImportError: cannot import name 'commands' from 'discord.ext' (unknown location) What to do?

maiden fable
warped mirage
#

i have a problem

maiden fable
#

Nice

warped mirage
#

today this shows and ```py
py : The term 'py' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a
path was included, verify that the path is correct and try again.
At line:1 char:1

  • py main.py
  • ~~
    • CategoryInfo : ObjectNotFound: (py:String) [], CommandNotFoundException
    • FullyQualifiedErrorId : CommandNotFoundException``` i get this error and if i do pip install nothing works
#

any ideas?

maiden fable
#

reinstall Python

warped mirage
#

do u actually need it

maiden fable
#

py is the basic Python launcher

#

if it isn't being recognized, that means a faulty installation

warped mirage
#

ok

slate swan
#

try python instead of py before doing that tho

maiden fable
heady sluice
#

chances are he's gonna become a pro and add pip to path without reinstalling python

maiden fable
#

Let's hope for that

warped mirage
#
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 1122, in call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 675, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 668, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'ban' raised an exception: AttributeError: 'Interaction' object has no attribute 'send'``` error  , ```py
@client.tree.command()
@commands.has_permissions(ban_members = True)
async def ban(ctx, member : discord.Member, *, reason: str):
    await member.ban(reason=reason)
    await ctx.send(f"{member.id} has been banned for {reason}")
    await member.send(f"You have been banned in {ctx.guild} for {reason}, Would you like to appeal? Join this server: hi")```
#

code ⏫

slate swan
#

you can create slashed like that

#

the naming convention is wrong

#

its interaction, not ctx, and its Interaction.response.send_message

#

even the checks have to be imported from app_commands

#

How can I create cogs in the new version of discord.py?

slate swan
paper sluice
#

huh?

slate swan
#

I'm educating people here?

paper sluice
slate swan
#

I wanna go drown in a glass of water again

still swan
#

!d discord.ext.commands.BucketType.default

unkempt canyonBOT
still swan
#

!d discord.ext.commands.BucketType.user

unkempt canyonBOT
slate swan
still swan
sick birch
paper sluice
#

too late, she already gone

silver pumice
#

Does it take some amount of time or something for an application command to show up in a server? \🤔

sick birch
#

hopefully she returns from her glass drowning shenanigans

sick birch
#

Commands registered to a single server are instantaneous

silver pumice
#

and that's with self.tree.copy_global_to?

slate swan
sick birch
#

dang okay

#

stay safe, it’s a dangerous glass of water out there

slate swan
#

thanks, Robin

swift pumice
#

i hate cogs

slate swan
#

why 😭 cogs are one of the most appreciatable things in dpy

swift pumice
#

i cant use them, idk how to use that shit. bruh

slate swan
#

what library?

prime marten
#

To anyone who is hosting their bot on heroku. How would I go about editing the code after everything is set up. Do I have to push the .py file again or is there some kind of editor in heroku? I'm new to this so sorry if this is a silly question

slate swan
#

updating your GitHub should trigger the update afaik

faint dagger
#

AttributeError: 'NoneType' object has no attribute 'is_connected' What to do?

#
@client.command()
async def play(ctx , arg):

    try:
        voice_channel = ctx.message.author.voice.channel
    except:
        print('Already connected or failed to connect.')

    from discord import voice_client
    if voice_client.VoiceClient.play(self=None, source=source):
        await ctx.send(f'{ctx.message.author.mention}, the music is already playing.')

    else:
        with YoutubeDL(YDL_OPTIONS) as ydl:
            info = ydl.extract_info(arg , download=False)

        URL = info['formats'][0]['url']

        voice_client.VoiceClient.play(discord.FFmpegPCMAudio(executable="ffmpeg\\ffmpeg.exe" , source=URL , **FFMPEG_OPTIONS))

        while voice_client.VoiceClient():
            await sleep(1)
        if not voice_client.VoiceClient.is_paused:
            await voice_client.VoiceClient.disconnect()```
shrewd apex
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

paper sluice
#

!ytdl

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
paper sluice
#

wdym? show example

daring olive
#

hey there, repost w/o the server invite

paper sluice
#

what lib is this?

#

you wont have to redo all ur code

#

only some part of it

#

then refer to the docs of that lib

faint dagger
#

how do I make 2 embeds go?

slate swan
silver pumice
#

What the heck does this mean?
TypeError: autocomplete callback 'name_autocomplete' requires either 2 or 3 parameters to be passed

#

I have

async def name_autocomplete(
        interaction: Interaction,
        current: str,
        namespace: Namespace
) -> list[Choice[str]]:
    ...
#

Nevermind, I just removed namespace

#

it was on the Gist from Rapptz, but I guess it shouldn't be there

uncut jacinth
#

So i got a view and i passed in ctx but i get a error how else could i ban a user with a button because ctx will not pass in

#
Traceback (most recent call last):
  File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 200, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\lequi\Desktop\Hint Bot v2\cogs\user.py", line 199, in info
    view.message = await ctx.send(embed = embed,view=view)
  File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\context.py", line 771, in send
    return await super().send(
  File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\abc.py", line 1541, in send
    state.store_view(view, ret.id)
  File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\state.py", line 368, in store_view
    self._view_store.add_view(view, message_id)
  File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ui\view.py", line 537, in add_view
    view._start_listening_from_store(self)
  File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ui\view.py", line 424, in _start_listening_from_store
    self.__timeout_expiry = time.monotonic() + self.timeout
TypeError: unsupported operand type(s) for +: 'float' and 'Button'

The above exception was the direct cause of the following exception:
#
Traceback (most recent call last):
  File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 1330, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 995, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\lequi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 209, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for +: 'float' and 'Button'
#
view = Whoisbuttons(ctx, member)
view.message = await ctx.send(embed = embed,view=view)
class Whoisbuttons(discord.ui.View):
    def __init__(self, ctx, member, timeout=13):
        super().__init__(timeout=timeout)
        self.ctx = ctx
        self.member = member

    async def on_timeout(self):
        for child in self.children:
            child.disabled=True
        await self.message.edit(view=self)

    async def interaction_check(self, interaction: discord.Interaction):
      if interaction.user != self.ctx.author:
        await interaction.response.send_message("You can't use that", ephemeral=True)
        return False
      return True

    @discord.ui.button(label="Timeout",style=discord.ButtonStyle.green)
    async def timeout(self,interaction:discord.Interaction,button:discord.ui.Button):
        print("Test")
slate swan
#

seems more like an internal issue

#

try updating the library

uncut jacinth
slate swan
#

weird

uncut jacinth
#

Do you have an alternate?

slate swan
#

idts try asking in the dpy server

torn sail
#

Because timeout is an attribute of view

paper sluice
#

lol, that was hiding in plane sight

uncut jacinth
#

Thank you :)

swift pumice
#

do you guys know a nsfw api(not anime, real)?

maiden fable
#

Not me

#

U can search google for "nsfw api" and u can find many there

swift pumice
#

okay

#

thanks

cerulean folio
#
async def fetch_ids(ctx, channel, message):
  if message.embeds:
    text  = re.findall('[0-9]+', message.embeds[0].description)
    for i in text:
      if not req.search_id(i) and not req.search(i):
        req.add_id(i)
  text  = re.findall('[0-9]+', message.content)
  if text:
    for i in text:
      if not req.search_id(i) and not req.search(i):
        req.add_id(i)

I have an unknown trouble with this code. req.search(i) will return True if a given user id is in A table, False otherwise. req.search_id(i) will return True if user id is in B table, False otherwise. req.add_id(i) will add a given id to B table.

When I replace req.add_id(i) by print('Added'), and add print(req.search_id(i), req.search(i)), I can see that it prints Added only if both are False which is what I want. Also tested my the sql functions, they search and add just fine.

However when I run the above code, the following error happens:

raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IntegrityError: UNIQUE constraint failed: ids.subject_id

Which means req.add_id(i) tried to add an existant ID (since it's a primary key that has to be unique). The SQL request inside this function is INSERT INTO ids(subject_id) VALUES(?); and I know I can just add to the SQL that it will add only in subject_id doesn't exist, but I'm just curious why this doesn't work when the conditions are working fine?? this function is not supposed to receive ids that already exists it's triggering my curiosity so much !

I would learn so much if someone can help me understand where the problem comes from ♥️

cerulean folio
#

it's just a python file where I wrote my sql functions :D

maiden fable
#

Ah okay

silver pumice
#

Uh... How come message.content is always '' for me?

maiden fable
#

What module?

cerulean folio
#

a module

swift pumice
maiden fable
#

@cerulean folio sorry I am not a SQL user, so u might wanna wait for someone like sarth/Robin to answer that

swift pumice
#

@cerulean folio nice big server you have there

sick birch
cerulean folio
swift pumice
silver pumice
#
Message received! message.content = ''

😔 why the heck

cerulean folio
silver pumice
maiden fable
#

!d discord.Intents.message_content

unkempt canyonBOT
#

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

• The message was sent by the client

• The message was sent in direct messages

• The message mentions the client

This applies to the following events...

cerulean folio
silver pumice
#

I wouldn't have thought anyone was using anything else

maiden fable
cerulean folio
cerulean folio
#

awww aw thank you ! ZhongHeart

silver pumice
maiden fable
#

Yea, Discord API Changes

paper sluice
cerulean folio
#

I tested it with the following code:

async def fetch_ids(ctx, channel, message):
  if message.embeds:
    text  = re.findall('[0-9]+', message.embeds[0].description)
    for i in text:
      print('____________________________')
      print(f'{not req.search_id(i)} and {not req.search(i)} gives:')
      print(not req.search_id(i) and not req.search(i))
      if not req.search_id(i) and not req.search(i):
        print('Added')
        # req.add_id(i)
  text  = re.findall('[0-9]+', message.content)
  if text:
    for i in text:
      if not req.search_id(i) and not req.search(i):
        print('Added')
        print('____________________________')
        # req.add_id(i)

Console output:

____________________________
True and True gives:
True
Added
____________________________
True and True gives:
True
Added
____________________________
True and False gives:
False
____________________________
True and True gives:
True
Added
____________________________
True and True gives:
True
Added

I don't know why my code won't work ><

#

The conditions are working fine, so home come req.add_id(i) receives an existing id as argument? 🤔

#

This drives me crazy it's not logical

paper sluice
#

what is req

uncut jacinth
#

Can i create a forum with a bot?

glad cradle
unkempt canyonBOT
#

Hey @fallow girder!

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

fallow girder
#

Anyone can help me ?

slate swan
#
    @commands.command(aliases = ["панель", "Панель", "профиль", "Профиль", "prof", "Prof", "p", "P", "п", "П", "g", "G", " g"])
    async def command_control_panel(self, ctx, member: discord.Member  = None):
        url = member.avatar.url # создал переменную URL аватарки пингуемого чела

        url1 = requests.get(url, stream = True) # Сделал юрл более оптимизированным
        url1 = Image.open(io.BytesIO(url1.content))
        url1 = url1.convert('RGBA') # конфертировал аву в РГБА
        url1 = url1.resize((300, 300), Image.ANTIALIAS)

sir, what could be wrong?

sick birch
#

You used the command without mentioning a user

heady sluice
#

I'd prefer using case_insensitive instead of ["панель", "Панель", "профиль", "Профиль", "prof", "Prof", "p", "P", "п", "П", "g", "G", " g"]

scarlet sorrel
#

Hey, bit of a difficult question, how do i set this to use better_exceptions instead of sys.stderr ? Basically what im asking is what file or whatever do i need to point it to

async def on_error(self, event_method, *args, **kwargs):
        """|coro|
        The default error handler provided by the client.
        By default this prints to :data:`sys.stderr` however it could be
        overridden to have a different implementation.
        Check :func:`~discord.on_error` for more details.
        """
        print('Ignoring exception in {}'.format(event_method), file=sys.stderr)
        traceback.print_exc()
fading marlin
#

override the event

slate swan
#
        font =  ImageFont.truetype('./Шрифты/picsel.ttf', size = 100, color=())

Dear. what to write to change the color of the text?

scarlet sorrel
fading marlin
#

wdym with what?

sick panther
#

Hi,
I was trying to overwrite the owner IDs of the developer portal, due some reasons. But for some reason it doesn't work as expected:

bot = commands.Bot(command_prefix=commands.when_mentioned, test_guilds=[897866866557603890, 966350034822135878], sync_commands=True, intents=disnake.Intents.all(), owner_ids=[456458873453150208, 688293803613880334]) 
bot.remove_command("help")

If I do check for the owner IDs with an if statement:

if ctx.author.id == bot.owner_ids

It returns False for some reason

fading marlin
#

this is basic python. Print author.id and owner_ids and see if you can find out why you're getting False

glad cradle
minor totem
#

Has anyone developed a configuration system at scale? I need pretty advanced configuration (should support types and functionality that JSON/YAML supports) for each guild my bot is in. My bot has multiple services and processes which currently is an API, Redis cache, PostgreSQL instance, interactions endpoint, gateway subscriber/watcher and finally a proxy.

While the bot isn't big currently. I am interested in how software which scales is designed and maintained so I am writing up this bot.

sick panther
slate swan
#
    @commands.command(aliases = ["панель", "Панель", "профиль", "Профиль", "prof", "Prof", "p", "P", "п", "П", "g", "G", " g"])
    async def command_control_panel(self, ctx):
        img = requests.get("https://drive.google.com/uc?export=download&confirm=no_antivirus&id=12sxQbdr-1t3QUe8dp3Cy8ennHPq5fpsS", stream = True) 
        img = Image.open(io.BytesIO(img.content))
        img = img.convert('RGBA') 

        idrawImg = ImageDraw.Draw(img)
        font =  ImageFont.truetype('./Шрифты/picsel.ttf', size = 60)

        author = ctx.author.name
        tag = ctx.author.discriminator
        text = f'{author}#{tag}'

        idrawImg.text((330, 40), text = text, font=font, fill = (91,141,199,255))
        url = ctx.author.display_avatar # создал переменную URL аватарки пингуемого чела

        url1 = requests.get(url, stream = True) # Сделал юрл более оптимизированным
        url1 = Image.open(io.BytesIO(url1.content))
        url1 = url1.convert('RGBA') # конфертировал аву в РГБА
        url1 = url1.resize((300, 300), Image.ANTIALIAS)

        url1M = Image.new('L', url1.size, 0 ) # Создал картинку. Где L означает черно белая для маски нужна. url1.size перенимает size. 0 прозрачность
        idrawM = ImageDraw.Draw(url1M) # говорим что переменной idrawM будем рисовать чтонибуить на url1M
        idrawM.ellipse((0, 0, 300, 300), fill=255) # Рисуем элипс. координаты 0 с права, 90 с верху, 1850 ширина, 1800 высота. 225 непрозрачная

        img.paste(url1, (406, 170), url1M)
        img.save('./ImageS/profile.png')

        file = discord.File("./ImageS/profile.png")

        await ctx.send(file=file, view=class_control_panel(ctx.author.id))

Dear, can you please tell me whether it is possible to make the text, regardless of the length, be in the center of the picture?

heady sluice
#

this was my method

counter = 190 - len(member.name) * 10
img_editable.text((counter, 100), text, (0, 0, 0), font=font)
#

where 190 was the end of my image, minus 10 per character in the member's name

#

the problem was, some characters were longer than others

#

but you can go around that with a complicated method, that for example counts all i's in the name or w's, and it's minus 5 per i and minus 15 per w

slate swan
fluid shadow
#

I am trying to use cogs for a reload command, and it seemed to work, but now all of my other commands are broken because 'ctx' isnt passed in.

class Commands(commands.Cog):
  @bot.command()
  async def d(self, ctx, arg):
    supported_docs = {
      'python': 'https://docs.python.org/3/search.html?q=',
      'discord': 'https://discordpy.readthedocs.io/en/stable/search.html?q=',
      'pandas': 'https://pandas.pydata.org/docs/search.html?q=',
      'numpy': 'https://numpy.org/doc/stable/search.html?q=',
      'scipy': 'https://docs.scipy.org/doc/scipy/search.html?q=',
      'pygame': 'https://www.pygame.org/docs/search.html?q=',
      
    }
    try:
      # await ctx.send(arg)
      arg = arg.split(' ')
      # await ctx.send(arg)
      arg = arg[0].split('.')
  
      await ctx.send(supported_docs[arg[0]] + arg[1])
    except KeyError as e:
      arg = ctx.message.content.split(' ')[1]
      key = 'python'
  
      print(e)
      await ctx.send(supported_docs[key] + arg)

discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.

Without cogs, I didn't need to pass it in. It would automatically be there. Any ideas?

slate swan
#
@bot.event
async def on_message(message):
    if "https://twitter.com" in message.content:
        string = message.content
        vxtwitter = string.replace('twitter.com', 'vxtwitter.com')
        webhook = await message.channel.create_webhook(name=message.author.display_name)
        await webhook.send(content=vxtwitter, avatar_url=message.author.display_avatar.url)
upbeat vigil
slate swan
#

the bot keeps spamming webhooks

#

any1 knows whats the problem

fluid shadow
slate swan
#

oooh so i acts like a loop ok

#

i know how to fix it thanks

#

Dear, tell me what kind of filter is this in the pillow

kindred epoch
fluid shadow
kindred epoch
#

You use commands.command instead of bot.command in cogs

#

Try looking at the cogs examples and how to use them in the docs

unkempt canyonBOT
#

Hey @fluid shadow!

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

scarlet sorrel
slate swan
#

hello someone knows how to make a bot like this? with my current time + a dnd status

#

please dm

scarlet sorrel
#

oh god

#

now the kids are even trying to make their bots Do Not Disturb

heady sluice
#

why even not

severe bone
#

In discord bot have a command right and how do I make it so if I type like !restock and add a text file it reads it and writes it in another txt file

sage otter
unkempt canyonBOT
#

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

Changes the client’s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter...
jovial urchin
#

Whats the most popular library for making discord bots?

sick birch
jovial urchin
#

like not maintained anymore

sick birch
#

It was

#

But not anymore

#

It un-discontinued

jovial urchin
#

So now its fine to use it again without having to worry about it being discontinued again?

sick birch
#

Fine to use it, yes. Worry about it being discontinued? Maybe

#

You being up a valid concern of how does one know if Danny won’t leave discord.py again?

#

Many are considering that, so good question

jovial urchin
#

So maybe disnake is the better choice to learn? Which is "better"?

sick birch
#

Better how?

#

You can make the decision for yourself of if you trust danny enough to continue developing it

jovial urchin
#

Idk, which library is easier to use, has more functionality, etc

sick birch
#

I can throw in my 2 cents but keep in mind it’s the opinion of a random guy on the internet

jovial urchin
#

U know more than me so please fire away

sick birch
#

Well, personally I believe discord.py is worth the risk, primarily because more people use it and ask for help with it. In terms of functionality, disnake and discord.py are almost identical, except for the different implementation but the end goal is still the same. Also disnake is relatively new, discord.py has been on for a good while and a de-facto, so there’s that

jovial urchin
sick birch
pliant gulch
#

You should also keep in mind whether or not you can read documentation, if you can’t you’ll probably end up relying on guides, there will be a difference in the available guides for each wrapper

jovial urchin
pliant gulch
#

The fork and the original will have different documentation as they bridge apart further

jovial urchin
#

I usually do. Is that something some people struggle with?

#

I mean its boring asf but i get it

pliant gulch
#

Yes some people try discord.py without some preq knowledge

#

But if you can read it, then you’ll be fine

jovial urchin
#

great ty

pliant gulch
#

I do find discord.py’s documentation to be a bit lacking when it comes to depth, like they don’t explain some of the API aspects very well

jovial urchin
#

Ah, is disnake better in that regard?

pliant gulch
#

I really have no clue, I haven’t taken a look so I’ll let you be the judge of that

#

I do know the maintainer has a lot of knowledge with the API and the gateway though

dusky pine
#

chill bro

#

it's just logging in using static token, have some patience

sick birch
#

I don’t know of anything called a “static token” and also it’s discord.Client, not discord.client?

dusky pine
#

for some reason dpy 2.0 turns logging level to INFO

sick birch
#

Well yeah I know of the logging module, though not sure what a static token is

dusky pine
#

afaik it's always been logging like that since 1.0

sick birch
#

Ah, so things are working as intended?

dusky pine
#

i think so

sick birch
#

Have you tried restarting the script?

frozen patio
#

How could I fix this?

#

I am reworking this into a database 🤔

#

Oh ok thanks

#

I did this for 1 server, and it worked fine when I put a channel ID in

#

But I want it in a database 😅

torn sail
dusky pine
#

static means non-changing iirc

torn sail
#

Yeah

frozen patio
#

I fixed it

#

It runs as expected

scarlet sorrel
maiden fable
maiden fable
scarlet sorrel
#

what i put there is the code to do that, but im just not sure what to replace sys.stderr with

maiden fable
#

Set that environment var

#

And it's gonna print automatically

#

(Acc to me it should)

scarlet sorrel
maiden fable
#

U don't replace that. sys.stderr represents the console, where the error is printed by default

scarlet sorrel
#

ok what part needs to be replaced then

maiden fable
#

Try removing the traceback.print_exc()

scarlet sorrel
maiden fable
#

Well, u need to try everything since I can't find the docs for the module that explain how to use it in the code

scarlet sorrel
#

If you don't know how to help maybe don't just say i should "try everything" lol

robust fulcrum
maiden fable
#

@scarlet sorrel how r u setting the environment variable?

scarlet sorrel
#

oh the one for better_exceptions

maiden fable
#

Yes

scarlet sorrel
#

dude iv already looked through all that, its all good, but you need to do some special stuff for coroutines

maiden fable
#

....?

#

I meant, are u using the terminal to set the variable or code

scarlet sorrel
#

dude i have better_exceptions working

maiden fable
#

Then?

scarlet sorrel
#

ugh

#

you need to do some special stuff for coroutines

#

as in, discord bots

maiden fable
#

I mean, what special stuff u talking about? For printing errors or smth?

scarlet sorrel
#

yes obviously printing errors

unkempt canyonBOT
#

better_exceptions/__init__.py lines 45 to 50

def format_exception(exc, value, tb):
    # Rebuild each time to take into account any changes made by the user to the global parameters
    formatter = ExceptionFormatter(colored=SUPPORTS_COLOR, theme=THEME, max_length=MAX_LENGTH,
                                   pipe_char=PIPE_CHAR, cap_char=CAP_CHAR)
    return list(formatter.format_exception(exc, value, tb))```
maiden fable
#

Try using this function

scarlet sorrel
#

yes i already know it works

#

oh you mean try that instead of the other one

#

ok 1 sec

#

thats not better_exceptions

maiden fable
#

.....?

scarlet sorrel
#

its not better_exceptions

#

its ".formatter"

maiden fable
#

Uh?

#

Wym by that

maiden fable
#

The be GitHub

scarlet sorrel
#

yea but what is that file

maiden fable
#

The _init_

scarlet sorrel
#

what do i do with it

maiden fable
#

Bro what r u even tryna convey

scarlet sorrel
#

what do i do with that code, just run it once and it fixes it, or put it at the start of the main file, or put it in the same folder or what

maiden fable
#

Have u ever used traceback.format_exception?

scarlet sorrel
#

nope

maiden fable
#

Ah, well it's just like traceback.print_exception, but it instead returns the list of lines of the exception

scarlet sorrel
#

ok well how do i make better_exceptions work for a coroutine/discord bot lol

maiden fable
#

So, better_exceptions.format_exception does the same thing. It returns the list of lines of the exception. U can change it to better_exceptions.format_exception(type(error), error, error.__traceback__)

#

In the on_error ^^^

scarlet sorrel
#

but I don't have that line anywhere

#

did i need to put better_exceptions.format_exception in the .py file for it to work? it works with other stuff

maiden fable
#

Yes

#

In the on_error event, remove everything and add that

scarlet sorrel
#

i dont have "on_error event"

maiden fable
#

Dude async def on_error

scarlet sorrel
#

🤷‍♂️ no one told me this lol

maiden fable
#

In dpy, everything prefixed with on_ is an event

scarlet sorrel
#

everyone said better_exceptions just works

#

and you dont need to add anything

#

ill add it now

cerulean folio
#

hi people !
somehow bot.fetch_user(764893681240637442) returns me this error:

    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In user_id: Value "Unknown" is not snowflake.
scarlet sorrel
#

@maiden fable

cerulean folio
#

here's the function where i use it:

async def search_id(bot, arg):
  try:
    return await bot.fetch_user(arg)
  except discord.NotFound:
    return False
maiden fable
cerulean folio
#

it works whatever you send it normally, i don't know why it won't work with this particular id :o

scarlet sorrel
cerulean folio
scarlet sorrel
cerulean folio
#

it used to scare the shit out of me now i somehow find this thingie so cute

scarlet sorrel
maiden fable
scarlet sorrel
tame nymph
#

D++ is a discord bot framework

maiden fable
maiden fable
tame nymph
#

Python is partly written in C++

maiden fable
#

C*

maiden fable
tame nymph
#

it contains C++

#

the repo suggests

maiden fable
#

Also, wait... The client.event isn't gonna work

#

Do u know about subclassing? @scarlet sorrel

scarlet sorrel
#

that took ages for us to get on the same page

maiden fable
#

Oof, okay... Then do one thing

#

Remove the @client.event

slate swan
tame nymph
#

cpython sungals

maiden fable
#

And do client.on_error = on_error before bot.run

scarlet sorrel
# maiden fable Oof, okay... Then do one thing

im kinda an outlier when it comes to coding, i only learn something new when i cant just work it out or use a way of doing it that i already know, and i only use coding to do things that i want to do, so i end up with a weird set of knowledge where im really good at string manipulation and AI prompt formatting stuff like that but i barely know how to make a function

slate swan
scarlet sorrel
#

thats why he did the emoji

pliant gulch
# tame nymph it contains C++

Half if not the majority of the files being flagged are headers in include/ which are being falsely detected as CPP, it would make sense to me if was an .hpp but it isn’t, and the rest are just tests using CPP

#

And utilities ^

slate swan
#

most of them are just .h files

pliant gulch
#

Yes, they are being falsely flagged as CPP files

slate swan
scarlet sorrel
#

@maiden fable

pliant gulch
#

I would accept if they were HPP files but they are just regular H files

#

And they don’t even utilise any of the stuff in CPP

scarlet sorrel
#

hunter please you're my only hope

#

🙏 for hunter to come back

maiden fable
slate swan
maiden fable
#

Do on_error(error, *args, **kwargs):

maiden fable
scarlet sorrel
#

like this tho?

slate swan
#

try it and see

slate swan
scarlet sorrel
slate swan
maiden fable
#

Ah, event_name

#

!d discord.Client.on_error

unkempt canyonBOT
#

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

The default error handler provided by the client.

By default this logs to the library logger however it could be overridden to have a different implementation. Check [`on_error()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_error "discord.on_error") for more details.

Changed in version 2.0: `event_method` parameter is now positional-only and instead of writing to `sys.stderr` it logs instead.
maiden fable
#

Gotcha. Do on_error(event_method, error): then

scarlet sorrel
maiden fable
#

Def

scarlet sorrel
maiden fable
#

It's fine

scarlet sorrel
cerulean folio
scarlet sorrel
scarlet sorrel
cerulean folio
#

hi people !
somehow bot.fetch_user(764893681240637442) returns me this error:

    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In user_id: Value "Unknown" is not snowflake.

here's the function where i use it:

async def search_id(bot, arg):
  try:
    return await bot.fetch_user(arg)
  except discord.NotFound:
    return False
slate swan
scarlet sorrel
slate swan
#

makes me wanna kick it like a ball

scarlet sorrel
slate swan
cerulean folio
slate swan
#

😳💍

#

imagine knowing how to eat okimii

scarlet sorrel
#

thats @slate swan pfp btw

robust fulcrum
#

@slate swan can you help me now?

scarlet sorrel
slate swan
#

fr

scarlet sorrel
robust fulcrum
#

Ok

#

But image is little.......

#

Anyway I'll not speak anymore

slate swan
#

its just a female eating ice cream bro

robust fulcrum
#

Ok

slate swan
#

nothing wrong with it

scarlet sorrel
slate swan
slate swan
robust fulcrum
#

Cause it's related it database

slate swan
#

i hate it when i press alt esc smh

#

tf does that even do

#

its a shortcut i have lol

#

more like a macro

cerulean folio
#

but even if i pass 4484 or 68438438 or ,fmlerzgu it will not send this one error

slate swan
#

...?

cerulean folio
#

what? lemon_scared

shrewd apex
#

?

magic pond
#
    @commands.command(hidden=True)
    @commands.guild_only()
    async def sync(self, ctx: commands.Context, sync_globally: bool = False) -> None:
      async with ctx.channel.typing():
        if ctx.channel.permissions_for(ctx.author).manage_guild:
            if sync_globally:
              
                await self.bot.tree.sync()
                await ctx.reply('Slash commands have been synchronized globally')
            else:
                self.bot.tree.copy_global_to(guild=ctx.guild)
                await self.bot.tree.sync(guild=ctx.guild)
                await ctx.reply('Slash commands have been synchronized on this server')
        else:
          embed = discord.Embed(title='Action Error', description='You don\'t have the permission to use this command.',color=0x2f3136)
          embed.set_thumbnail(url='https://cdn.discordapp.com/emojis/971007299038621727.webp?size=128&quality=lossless')
          embed.set_footer(text=f'Requested by {ctx.author}')
          await ctx.reply(embed=embed)

is this correct ?

#

it just shows tht my bot is typing but does not sync the commands

#

this command used to work before

slate swan
#

does anyone know how to make a global chat for discord bot python

#

wdym by global chat?

#

just lile yggdrasil ig

#

like*

slate swan
slate swan
#

nice

#

????...

shrewd apex
slate swan
#

no lol

#

It's a bot

shrewd apex
#

ik a bot name

slate swan
#

It has welcome stuff

shrewd apex
#

just fun facts

dusky pine
slate swan
#

if iirc

cerulean folio
#

guys can someone help me with a sql request?
I need to SELECT * FROM tableA WHERE value1 < 3 AND NOT EXISTS(SELECT 1 FROM B WHERE B.ID=A.ID) basically, but there are fragments that i don't know how to do

#

idk i'm confused

visual island
cerulean folio
#

yes !

robust fulcrum
#

Sqlite is very difficult to use

vocal snow
robust fulcrum
#

Everything

visual island
#

Maybe you just haven't learn much about it?

robust fulcrum
#

Today sqlite broke my brain

#

Me was making custom prefix for my discord bot

#

But finnaly i gave up

cerulean folio
#

lol

#

I can help you set it up in DM if u want @robust fulcrum

slate swan
#

sqlite3 is easier than most of the databases, and a prefix system is really easy to implement

robust fulcrum
#

@slate swan

#

Whats meaning of setup_hook

slate swan
#

how can i have a clickable link in embed description

#

anyone here?

#

didn't work

#

show code?

#

i mean

#

like is it possible to have it without the https link

#

like it goes to www.google.com instead of https://google.com

#

ooooooooooh i get it

#

my bad

robust fulcrum
#

Ig

dusky pine
robust fulcrum
#

Me never used sqlite

#

Can you help me ?

#

I'll not ask for everything just help where i get stuck

dusky pine
#

yeah sure

robust fulcrum
#

At dm?

dusky pine
#

just here

robust fulcrum
#

Ok

dusky pine
slate swan
unkempt canyonBOT
#

main.py line 24

await bot.change_presence(activity=discord.Activity(type=beats_activity[0], name=beats_activity[1]),status=discord.Status.dnd)```
`modules/impfunctions.py` line 30
```py
response = requests.get("https://memes.blademaker.tv/api?lang=en")```
`cogs/general.py` line 97
```py
for guild in self.bot.guilds:names.append(f"**`​{guild.name}`​**")```
slate swan
#

don't change status in on_ready

#

um wot can i do?

#

use async libraries, aiohttp in your case

#

maybe can u do a pr?

#

and you can use a list comprehension instead of that for loop

slate swan
#

yea

#

np ill try to fix it

unkempt canyonBOT
#

Do you ever find yourself writing something like this?

>>> squares = []
>>> for n in range(5):
...    squares.append(n ** 2)
[0, 1, 4, 9, 16]

Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:

>>> [n ** 2 for n in range(5)]
[0, 1, 4, 9, 16]

List comprehensions also get an if statement:

>>> [n ** 2 for n in range(5) if n % 2 == 0]
[0, 4, 16]

For more info, see this pythonforbeginners.com post.

shrewd apex