#discord-bots

1 messages · Page 911 of 1

narrow grail
#

It‘s not only working when making a message Command, it also doesn‘t work when I make a command where the bot should join my voice channel

brittle flume
#

Is there any good cheap bot hosting site?

left crater
#

you can try aws or heroku but they are not that good

#

i think google also does hosting

brittle flume
#

Like anything <= 1$

narrow grail
supple thorn
brittle flume
viscid relic
#

What is that?

#

Code:
@client.command()
async def factorial(ctx, number):
n = int(number)
if n > 20:
await ctx.send("Error")
if n <= 1:
await ctx.send(n)
else:
n = n*factorial(n-1)
await ctx.send(n)

maiden fable
#

Ah

#

Recursion

#

You are calling the factorial function

#

Your command name

heavy folio
#

the function in which you are doing stuff in

gaunt ice
heavy folio
#
def funcname():
    funcname()
heavy folio
gaunt ice
#

ye

winged bone
#

how do I correctly annotate a User | Member? Do I always have to write the union?

rocky trench
#

I don't really get what you're asking

vocal plover
winged bone
#

is there even a difference?

vocal plover
#

iirc if you put User first then it will always be coerced into a user

#

since members are valid users

#

but users may not be valid members

winged bone
#

ok

viscid relic
#

How to fix this?

#

Code :
@client.command()
async def factorial(ctx, number):
if number >= 20:
if number <= 1:
await ctx.send(number)
else:
number = number*factorial(number-1)
await ctx.send(number)
else:
await ctx.send("Error")

vocal plover
#

you need to typehint number as an int else discord.py will treat it as a string

#

so number: int

#

also that function won't work properly when you get further in since you're calling it recursively but you call it with the wrong parameters and it doesnt return a value, you may want to take a look at

#

!d math.factorial

unkempt canyonBOT
#

math.factorial(x)```
Return *x* factorial as an integer. Raises [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "ValueError") if *x* is not integral or is negative.

Deprecated since version 3.9: Accepting floats with integral values (like `5.0`) is deprecated.
lilac plover
#

hi

slate swan
#
async def Help(ctx):
  await ctx.send(
    "Click below to get help embed",
    components = [
       Button(label = "Yes", custom_id = "button5", style=ButtonStyle.green),
       Button(label = "No", custom_id = "buttons123", style=ButtonStyle.red)
    ],
  )

  interaction = await client.wait_for("button_click", check = lambda i: i.custom_id == "button5", timeout=120)
  await interaction.send(f"{helpEmbed}")
  
  interaction = await client.wait_for("button_click", check = lambda i: i.custom_id == "button123", timeout=120)
  await interaction.send("Not sending help embed!")```

this is my code k?
thebot  runs without errors
the command works
but upon clicking the buttons
interaction failed
no errors in console
lilac plover
#

like to check if theres any resources for discord sales bot?

vocal plover
slate swan
#

from discord_components import DiscordComponents, ComponentsBot, Button, ButtonStyle

vocal plover
#

ah I'm not familiar with discord_components sorry

slate swan
#

um

#

k

slate swan
vocal plover
#

uh v2 of most libs (discord.py, nextcord, disnake, etc.) support a construct called 'Views' which allows you to neasily manage components, I can link the documentation for that if you want

maiden fable
#

👀

lyric tusk
#

how do u use slash commands in a cogs

vocal plover
lyric tusk
#

nextcord

vocal plover
honest vessel
#

are there like any examples with images so u can see what all those are looking like?

vocal plover
#

the code or the actual things in discord?

honest vessel
#

yeah like demo how it looks in discord

#

so i know what i am looking for

vocal plover
honest vessel
#

ah thanks

#

ok so if am looking for a pagening with disnake i want?

flat solstice
#

so I'm syncing my d.py 2.0 command tree during on_ready, is it possible to do that during the setup_hook or does it require the guilds cache to be filled in (I'm thinking it does)

maiden fable
flat solstice
#

okay

flat solstice
# maiden fable I don't think it needs the cache since it sends the data to the Discord API

okay so either something is going really wrong or the tree doesn't get given the app ID until on_ready is calledpy Traceback (most recent call last): return future.result() File "C:\Users\Teagan\Documents\Coding\Zupie\bot\utils\services.py", line 162, in main await self.start(token) File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\client.py", line 655, in start await self.login(token) File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\client.py", line 521, in login await self.setup_hook() File "C:\Users\Teagan\Documents\Coding\Zupie\bot\utils\services.py", line 138, in setup_hook await self.tree.sync(guild=Object(id=default_guild))# File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\app_commands\tree.py", line 742, in sync raise ClientException('Client does not have an application ID set') discord.errors.ClientException: Client does not have an application ID set Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000192B116E680> Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 116, in __del__ self.close() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 108, in close self._loop.call_soon(self._call_connection_lost, None) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 745, in call_soon self._check_closed() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 510, in _check_closed raise RuntimeError('Event loop is closed') RuntimeError: Event loop is closed

maiden fable
#

Idk, try using a task

spring flax
#

if I have a ```py

def is_modmail_channel():
    async def predicate(self, ctx):
        if not (await self.check_if_open_with_channel(ctx.channel.id)):
            await ctx.send(disnake.Embed(description="This channel is not a ModMail channel", color=disnake.Color.red()))
            return False
        else:
            return True
    return commands.check(predicate)
how do I use this as a deco for a command?
#

If I just do

@commands.command()
@is_modmail_channel()

It'll say it requires ctx
but if I put ctx, it says ctx, isn't defined

spring flax
#

i'm not supposed to put it under my cog class?

#

oh well that makes sense

placid skiff
#

the correct usage, for example, is this one:

def is_call_manager()->Callable[[T], T]:
    def predicate(ctx: AnyContext)->bool:
        result = db.field("SELECT WhiteListRoleID FROM Guild WHERE GuildID IS?", ctx.guild.id)
        if result is not None and any(role.id == result for role in ctx.author.roles):
            return True
        else:
            raise WhiteListFailure(message="This user hasn't the permission to manage calls")
    return check(predicate)

with AnyContext equals to typing.Any(disnake.ext.commands.Context, dinsake.ApplicationCommandInteraction) if you use slash commands too

spring flax
#

huh

#

how did that come

placid skiff
spring flax
#

okay

#

what if I put the check inside the same cog file but not in the cog class?

placid skiff
#

my path for example is like this:

-My_bot
  -Cogs
    -my_cogs.py
  -checks
    -my_checks.py
#

then in my cogs script i import checks.my_checks.function_name and use @function_name before the command

placid skiff
#

take all checks inside a folder is more readable of course

spring flax
#

yeah it's because part of my check uses a function that's in my cog file

placid skiff
#

if they are reliable to checks then is useless to declare them inside the cog file, otherwise you can create another external folder in your bot folder where you can create your script and then import them, like:

-My_bot
  -Cogs
    -my_cogs.py
  -checks
    -my_checks.py
  -utils_script
    -scripts.py
flat solstice
#

is there a way to view the cache? like to print it / export it to a redis session

placid skiff
#

in that utils folder you can declare function that will come always useful

spring flax
spring flax
placid skiff
unkempt canyonBOT
placid skiff
#

i dunno if there is a member cache but i don't think so

placid skiff
flat solstice
placid skiff
placid skiff
#

where users is the list of user that the bot can see

#

and the same could be for the guilds

#

for channels instead they are stored in guild object, discord.Guild.text_channels and discord.Guild.voice_channels

spring flax
#

wait in my cog file, not in the cog class, how do I access bot?

placid skiff
# spring flax wait in my cog file, not in the cog class, how do I access bot?

cogs are declared like this:

class myCog(Cog):
  def __init__(self, bot):
    self.bot = bot

def setup(bot):
  bot.add_cog(myCog(bot))

the setup function is called by the instance of your bot (i don't know how, if you are curious you can check the source code) and the setup function create an instance of your cog with passing the bot instance in it

#

so you can access bot method by doing self.bot.method() in your cog

spring flax
#

no not in the cog class

flat solstice
#

think you'd have to import the bot var from it's file, at least that's what I ended up doing

placid skiff
#

it will raise a circular import if you import your bot inside a cog file

spring flax
#

in a cog file:

import disnake
from disnake.ext import commands

x = bot.something
 
class Cog(commands.Cog)
  #code
flat solstice
spring flax
placid skiff
spring flax
#

how do I access it

flat solstice
placid skiff
flat solstice
cloud dawn
#

Defining bot vars is then just self.var

#

You then import the class

spring flax
flat solstice
spring flax
#

okay will try

placid skiff
#

uhm all those question racked my brains btw hahaha

flat solstice
spring flax
#

why does this still raise TypeError: ModMail.is_modmail_channel.<locals>.predicate() missing 1 required positional argument: 'ctx'

placid skiff
#

code

flat solstice
#

anyone know which part of @unkempt canyon's source handles displaying GitHub code (you know when you send a link to a GitHub repo and the bot replies with a msg showing that file or a line of the file)

spring flax
# placid skiff code
#imports
async def check_if_open_with_channel(channel_id):
    async with bot.db.execute("SELECT modmail_channel from modmail_channels WHERE modmail_channel = ?", (channel_id,)) as cursor:
        data = await cursor.fetchone()
        if not data:
            return False
        return True


def is_modmail_channel():
    async def predicate(ctx):
        if not (await check_if_open_with_channel(ctx.channel.id)):
            await ctx.send(disnake.Embed(description="This channel is not a ModMail channel", color=disnake.Color.red()))
            return False
        else:
            return True
    return commands.check(predicate)
    
#cog class ```
I'm using it as a deco in one of my cog commands like just `@is_modmail_channel()`
placid skiff
#

is passed

spring flax
#

what??

placid skiff
#

whait why async def predicate?

spring flax
#

because i'm using await

#

but I don't need to

unkempt canyonBOT
#

@slate swan :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | TypeError: myfunc() missing 1 required positional argument: 'x'
spring flax
#

!e ```py
def myfunc():
async def test(x):
print('test')
myfunc()

unkempt canyonBOT
#

@spring flax :warning: Your eval job has completed with return code 0.

[No output]
#
Resources

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

spring flax
#

isn't that what i'm doing there too?

#

in the deco i'm not calling the async function

raven matrix
#

How to make Discord commands?

placid skiff
#

As i thought there is no need to declare predicate as async function

slate swan
#

how can i get a specific text of a string?

for example i want to get every user id and their xp

**#1 I usrid XP: `185`**
#2 I usrid XP: `180`
#3 I usrid XP: `91`
#4 I usrid XP: `83`
:sparkles: **More?** `#top text day`
placid skiff
#
 if inspect.iscoroutinefunction(predicate):
        decorator.predicate = predicate
    else:

        @functools.wraps(predicate)
        async def wrapper(ctx):
            return predicate(ctx)  # type: ignore

        decorator.predicate = wrapper

    return decorator  # type: ignore

this is a part of the check function in disnake.py source code

spring flax
#

no i don't need self

#

i mean ctx

#
#in a checks file
def something():
    async def predicate(ctx):
        #code

    return commands.check(predicate)

####
@commands.command()
@checks.something()
async def ...
quick gust
#

lets try to stay a bit calm

spring flax
#

this works ^

#

maybe because you're wrong?

gaunt ice
#

SUGGEST ME

placid skiff
#

Bro he has the ctx in his check, that is not the issue

maiden fable
placid skiff
#
def is_modmail_channel():
    async def predicate(ctx):
        if not (await check_if_open_with_channel(ctx.channel.id)):
            await ctx.send(disnake.Embed(description="This channel is not a ModMail channel", color=disnake.Color.red()))
            return False
        else:
            return True
    return commands.check(predicate)

This is his check

spring flax
placid skiff
#

as you see, predicate has ctx, the problems is something else

maiden fable
#

Ah

maiden fable
placid skiff
#

first of all, the predicate function doesn't need to be declared as an async function

maiden fable
#

It can be

placid skiff
maiden fable
#

!d discord.ext.commands.check

unkempt canyonBOT
#

@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").

These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event.

If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
placid skiff
#

Read the code that i sent from the source code

spring flax
#

for the database operation

maiden fable
#

Bro, if he uses await inside a non async function, it will raise an error at his end

placid skiff
#

...

maiden fable
#

See

unkempt canyonBOT
#

@slate swan :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 2
002 |     await
003 |          ^
004 | SyntaxError: invalid syntax
placid skiff
#

cames from check function from the source code

maiden fable
unkempt canyonBOT
#

@slate swan :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 5
002 | SyntaxError: 'await' outside async function
placid skiff
#

Well nevermind already tired to explain, the problem could be the decorator so @spring flax send the command

maiden fable
placid skiff
#

Bro you can't relate on the error code, it helps but it is not said that the issue is what you think, because if you read his decorator, ctx is defined inside the function

maiden fable
#

@spring flax can you share yr check code?

final iron
placid skiff
#

the issue could be when he called the decorator

maiden fable
final iron
placid skiff
#

EXACTLY, when he used it, so we have to check when the decorator is called, you were telling him that he didn't declared ctx D_D

hoary cargo
#

i arrived when drama again damn MR_canny_9

placid skiff
#

nvm just try to solve this issue

maiden fable
#

@slate swan @placid skiff can we please calm down?

placid skiff
#

.. note::
The function returned by predicate is always a coroutine,
even if the original function was not a coroutine.

Here it is a note from the source code btw

maiden fable
#

Sooo?

#

Dude I just showed u an example from the dpy server

placid skiff
#

so is not necessary that predicate is async

maiden fable
#

That's how u should use the deco tho

vale wing
#

^

maiden fable
#

How can you call an async function inside a normal function

hoary cargo
#

well, there are various ways to do this anyway lol

maiden fable
#

.....?

unkempt canyonBOT
#

@discord.ext.commands.check_any(*checks)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if any of the checks passed will pass, i.e. using logical OR.

If all checks fail then [`CheckAnyFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckAnyFailure "discord.ext.commands.CheckAnyFailure") is raised to signal the failure. It inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Note

The `predicate` attribute for this function **is** a coroutine.

New in version 1.3.
placid skiff
vale wing
#

asyncio.run_coroutine_threadsafe() ?

maiden fable
#

I think I'mma go away before I lose my cool

hoary cargo
#

artistic_hmm good choice

placid skiff
#

i just don't understand why are you complaining it if even the documentation says that is not necessary D_D

vale wing
#

What the living hell

maiden fable
#

Why using check_any

vale wing
#

Okay seems legit but why not make the outer function a coro as well

hoary cargo
#

you overcomplicated that shit so much

slate swan
vale wing
#

Np

#

Use \d with the number modifiers

placid skiff
vale wing
#

If there are not gonna be any other numbers

vale wing
maiden fable
#

lemon_pensive can we seriously stop it now?

placid skiff
vale wing
#

Ok

unkempt canyonBOT
#

@slate swan :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 5
002 | SyntaxError: 'await' outside async function
sage otter
#

I mean you don’t really need the check_any. It’s designed to accept multiple checks and return if any of them return true.

vale wing
#

Anyways who needs decorator checks when you have cog checks 😏

placid skiff
#
if inspect.iscoroutinefunction(predicate):
        decorator.predicate = predicate
    else:

        @functools.wraps(predicate)
        async def wrapper(ctx):
            return predicate(ctx)  # type: ignore
``` now read this code an tell me what it does .-.
mossy wasp
#

What is the easiest way to just. Send a message in a server?

placid skiff
#

wtf? wdym?

vale wing
hoary cargo
mossy wasp
#

or server

vale wing
#

Yes but not including the brackets I hope yk python right

placid skiff
#

bro that is not a code of mine or something, that block of code is written inside the check function of discord.py, it checks if the predicate that you pass in the check is a coroutine function, if it isn't it turns the predicate in a coroutine. That's all, what is hard with that?

vale wing
#

🤯

sage otter
#

You guys are really talking about bots anymore. Might wanna chill before Hunter pulls out the ot-shit 👌

sage otter
#

Not really? It’s completely irrelevant

placid skiff
sage otter
#

AMshrug ok then

unkempt canyonBOT
#

@slate swan :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 5
002 | SyntaxError: 'await' outside async function
placid skiff
#

ok example time. one sec.

hoary cargo
#

MR_canny_meh_stage is this a joke

vale wing
#

!e

import asyncio

async def f():
    print('hi')

asyncio.run_coroutine_threadsafe(f(), asyncio.new_event_loop())```
unkempt canyonBOT
#

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

001 | sys:1: RuntimeWarning: coroutine 'f' was never awaited
002 | RuntimeWarning: Enable tracemalloc to get the object allocation traceback
vale wing
#

Ok

rocky trench
#

You can't use await in a non async function.

#

Basic python smart

#

It like literally.. doesn't work

#

It will raise an exception

#

Clear enough to me

#

!e

async def print():
    print('hello')

def proof():
    await print()
proof()```
unkempt canyonBOT
#

@rocky trench :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 5
002 | SyntaxError: 'await' outside async function
rocky trench
#

^^

vale wing
#

Will an exec command that can execute async functions be considered a solid proof, cause I have one

slate swan
#

i mean

vale wing
#

2 mins

rocky trench
#

Ive got time

slate swan
#

bot had a property which gives you an asyncio loop ( idr )

rocky trench
#

U didnt use await inside a function without async

#

Which is what they said that was possible

cosmic agate
#

hey guys

#

  name = random_sub.title
  url = random_sub.url
  likes = random_sub.score
  comments = random_sub.num_comments
  link = random_sub.selftext

  button = Button(label="Next Meme", style=nextcord.ButtonStyle.green)

  async def meme(self, interaction):
    await interaction.response.edit_message(title = name, url = url, colour=nextcord.Colour.random())


  view = View()  
  view.add_item(button)
  em = nextcord.Embed(title = name, url = url, colour=nextcord.Colour.random())
  em.set_image(url = url)
  em.set_footer(text =f"👍: {likes} | 💬: {comments}")

  await ctx.send(embed= em, view=view)
``` this my code for meme (there is more but its confidentional stuff)
rocky trench
#

Anyways, anyone knows how I can make my bot send tracebacks?

cosmic agate
#

apparently when i click the button, it does not give me a new meme

rocky trench
#

Basicly, I don't know how to do it. Just if there is an error, so it sends it in chat

vale wing
#

Um I can't get into github wtf

cosmic agate
#

guys help

maiden fable
#

Cool!

vale wing
rocky trench
#

!e
Like python bot:

def function():
    list= []
    print(list[0])
function()```
unkempt canyonBOT
#

@rocky trench :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 4, in <module>
003 |   File "<string>", line 3, in function
004 | IndexError: list index out of range
rocky trench
#

Like this

cosmic agate
#

guys help

slate swan
#

do you mean that that the predicate def cannot be an async one?

cosmic agate
#

@maiden fable help?

#

pls sorry for ping

rocky trench
#

What's the point of pinging a random guy

maiden fable
cosmic agate
rocky trench
slate swan
#

well you're right
😅 i didnt read the complete chats so i got you wrong.

maiden fable
sick birch
#

Is nextcord a d.py fork?

cosmic agate
#

yessir i use it

sick birch
#

Ok. then the method should be the same in d.py

final iron
sick birch
#

You're missing the nextcord.ui.button decorator

cosmic agate
#

yeah just change name from discord to nextcord

cosmic agate
vale wing
#

The link is weird

hoary cargo
cosmic agate
#

yeah

#

but in this case no

rocky trench
#

Hmm. So it's like not possible?

vale wing
#

Ok

hoary cargo
rocky trench
#

I'll do it when I'm at home

vale wing
#

In on_command_error it is None

#

So not even worth a try, already tried to implement such thing

#

Maybe we just need to catch more low-level stuff, like use on_error instead of on_command_error but I haven't ever tried that

placid skiff
#

it is possible anyway, i just don't remember how and can't find the discussion that i had with the guy who explained this to me. i'm getting C:\Users\giacomo.dimatteo\PycharmProjects\ZhagoBot\lib\bot\bandi_check\Checks.py:69: RuntimeWarning: coroutine 'is_me.<locals>.predicate' was never awaited wrapper(ctx)

vale wing
placid skiff
#

and the code is:

def is_me()->Callable[[T], T]:
    def predicate(ctx: AnyContext)->bool:
        @functools.wraps(predicate)
        async def wrapper(ctx):
            return predicate(ctx)
        wrapper(ctx)
    return check(predicate)
unkempt canyonBOT
#

discord/ext/commands/bot.py line 233

traceback.print_exception(type(exception), exception, exception.__traceback__, file=sys.stderr)```
placid skiff
#

essentially what i am doing is converting the predicate function into a coroutine function,

#

it's not like predicate will not be an async function, it will be a coroutine function, but not a declared one

hoary cargo
slate swan
sick birch
#

Use the traceback library to get it

placid skiff
#

btw reading this The check functions for command 'stupid_command' failed is a little bit hilarious

maiden fable
sick birch
#

They wanted to print it on discord

hoary cargo
#

raise the discord MR_canny_12

maiden fable
sick birch
#

Honestly printing errors to console isn't that great, instead you could probably send all your errors somewhere else, I know there are platforms for that for watching for errors, or set up an admin bot dashboard to view errors

slate swan
#

looli make your own API and send your errors to the API using POST reqs

sick birch
#

Yep that works just as well

#

Store the errors in database and make a web app using maybe next.js and use something like getServerSideProps to render the errors

pliant gulch
#

What databases are able to properly store Exceptions?

#

You'd probably need to make a custom type, and an array for it?

narrow grail
#

how to play a audio file?

#

on replit

terse blade
#
async def embed(ctx):
  experience = users[f'{ctx.author.id}']["experience"]
  userlvl = users[f'{ctx.author.id}']['level']
  embed = discord.Embed (description=('Your rank is: {userlvl}'),
  set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url)
  await ctx.send(embed=embed))```
why does this not work
cerulean elbow
terse blade
cerulean elbow
terse blade
cerulean elbow
terse blade
cerulean elbow
#

Same thing.

terse blade
#

it really isnt

cerulean elbow
rocky trench
#

Its not the level system

cerulean elbow
rocky trench
#

Its not the same thing then

terse blade
#

no?

hoary cargo
slate swan
#
    pass```
be like
slate swan
pliant gulch
hoary cargo
slate swan
pliant gulch
slate swan
#

but storing exceptions is just a great fucking idea

#

you can just look at them later and fix them as they're stacked up

terse blade
#

what would authors url be

grim oar
#

Wtf use logging

terse blade
#

who

grim oar
unkempt canyonBOT
#
Nah.

No documentation found for the requested symbol.

grim oar
#

Ok

terse blade
grim oar
#

author is a member or user

slate swan
#

probably wouldn't store the whole object, just the line, description, name of the exception

rancid stump
#

hello i want to send text file through bot can i can do that with this code ?

slate swan
#

!d discord.Asset.url | get the Asset with Member.avatar

unkempt canyonBOT
unkempt canyonBOT
#

Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:

# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")

# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
    file = discord.File(f)

When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.

discord.Embed instances have a set_image method which can be used to set an attachment as an image:

embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png")  # Filename here must be exactly same as attachment filename.

After this, you can send an embed with an attachment to Discord:

await channel.send(file=file, embed=embed)

This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.

slate swan
#

well same logic here

#

not exactly the same thing, but almost

grim oar
terse blade
#

ctx.author.avatar.url
whats this ment to be

slate swan
slate swan
#

what did I say against it

grim oar
#

Why you storing exceptions in a database

slate swan
#

cuz it's faster and better practice

grim oar
#

No it's not

slate swan
#

and it's easier to use in the future

slate swan
slate swan
slate swan
# terse blade wym?

!d discord.Member.avatar read the description it can be None, so when you will use .url it will raise an attribute error

#

!d discord.User.avatar

unkempt canyonBOT
#

property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/master/api.html#discord.Asset "discord.Asset") for the avatar the user has.

If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.display_avatar "discord.User.display_avatar").
slate swan
rancid stump
slate swan
#

I can also use a database from anywhere

#

Show code

rancid stump
terse blade
slate swan
terse blade
#

AttributeError: 'Member' object has no attribute 'display_avatar'

slate swan
terse blade
#

1.7.3

slate swan
#

hm .avatar and other are for 2.0+
You may just use Member.avatar_url
Or update to 2.0 for using these properties

terse blade
#

updating then 🤣

terse blade
slate swan
#

Code ?

terse blade
#

actually no commands work now tf

slate swan
#

hm, on_message moment

#

do you have that "event"?

terse blade
#

there gonna be slash commands so thats useless

slate swan
#

if yes, change the decorator from .event to .listen()

terse blade
slate swan
#

you got that event or not?

terse blade
#

@bot.listen()
async def on_message(message):

#

so this?

placid skiff
#

what's going on here seems like an interesting issue

terse blade
#

my commands dont work now

placid skiff
#

code of the command

slate swan
#

God is typing

slate swan
#

whenhmmcat

terse blade
slate swan
#

wut

terse blade
placid skiff
#

code of the command which doesn't run

slate swan
#

^

slate swan
terse blade
#

the commands dont work but everything else does

final iron
#

Hello chat

placid skiff
#

SEND THE CODE

final iron
#

What's going on

terse blade
#
async def test(ctx,*, text):
  embed = discord.Embed(description=text)
  await ctx.send(embed=embed)```
slate swan
#

Can you like paste your complete code somewhere

#

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

placid skiff
#

if it is in one file xD

terse blade
slate swan
#

cogs won't affect the commands in any ways tho

final iron
terse blade
final iron
# terse blade TEST DATABASE

What's the point of making a test database with JSON if you're just going to have to change all your code when you get out of the "testing" phase

slate swan
#

Since it might take time to send the request to discord sometimes

terse blade
final iron
#

Which means it's not a test database and it's your long term database

#

Which is a terrible idea

terse blade
#

why

#

it works

final iron
#

Read this

slate swan
#

.

final iron
#

Also something I have to add on is that you're eventually going to end up in JSON hell

terse blade
#

so why do commands not work?

vocal plover
#

heartbreak latency might just be the best typo ever

terse blade
#

still dont work

ivory juniper
#

Jesus is proud of you

placid skiff
#

if not f'{user.id}' in users: wth is this shit?

slate swan
#

I'll simply blame my keyboard's autocorrect for that and pretend that nothing happened

vocal plover
terse blade
slate swan
terse blade
slate swan
#

Latency is not related to your internet tho, just try printing it inside an on_ready event

terse blade
#

1ms

slate swan
terse blade
#

Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0ms

slate swan
#

That's not what I asked for mate, print bot.latency

terse blade
#

0.11692290000000005

slate swan
#

😩 that's not the issue then

terse blade
#

so nothing is

placid skiff
#

when does your commands stopped working?

slate swan
#

Last question Are you running the correct bot?

terse blade
terse blade
slate swan
#

I mean does your bot even get online

terse blade
#

yes

#

cause it collects xp

placid skiff
slate swan
#

How did you invoke the command?

terse blade
#

oh as in time?

placid skiff
#

Your command worked before?

#

they ever worked?

terse blade
placid skiff
#

ok when they stopped working?

terse blade
#

when i updated from 1.7.3 to 2.0.0a it stopped

#

so...

slate swan
#

Wait I know what happened

placid skiff
#

check asyncio last version please

slate swan
#

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

slate swan
#

It's a privelaged intent now

#

and you need it for commands to work

placid skiff
#

uhm so your bot now needs this even to execute commands? cool

flat solstice
flat solstice
slate swan
terse blade
placid skiff
#

so essentially if one of my bot exceeds 100 or more servers it will stop working entirely until they verify it

slate swan
narrow grail
#

is it possible to import a event from an other file ?

slate swan
#

cogs

#

!d discord.ext.commands.Cog

unkempt canyonBOT
#

class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/master/ext/commands/cogs.html#ext-commands-cogs) page.

When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
slate swan
#

!d discord.ext.commands.Bot.add_listener

unkempt canyonBOT
#

add_listener(func, name=...)```
The non decorator alternative to [`listen()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
slate swan
#

Or this

#

wut

#

he ment an event in another file

narrow grail
slate swan
slate swan
# slate swan wut

They can just import the function and add_listener(function, name)

narrow grail
#

@slate swan also import discord.ext to this other file?

unkempt canyonBOT
#

discord/ext/commands/cog.py lines 523 to 524

for name, method_name in self.__cog_listeners__:
    bot.add_listener(getattr(self, method_name), name)```
narrow grail
#

why is this so complicated? I only want to import the message.author to the other file, to put it in the list where I add random messages

honest vessel
#

easy i guess if use cogs and decorations

#

@slate swanprob a personal preference

narrow grail
honest vessel
#

make an event aka listener???

#

that delete is weird

#

where is count= and userid=

#

count=3 AND userid=?

final iron
#

Easy peasy

honest vessel
#

prob made cogs wrong

narrow grail
final iron
#

yikes

narrow grail
final iron
#

That's why you should learn python before making a Discord bot

vale wing
#

Oh nvm

narrow grail
#

but I never needed cogs before

#

and classes too

honest vessel
#

u can have multi events of same in cogs

#

or do i missunderstand u?

cerulean elbow
honest vessel
#

@narrow grailhere is a cog

class IRL(commands.Cog):
    def __init__(self, bot):
        self.bot = bot


    @commands.Cog.listener("on_member_join")
    async def on_member_join(self, member : disnake.Member):
        print(member)



def setup(bot):
    bot.add_cog(IRL(bot))
narrow grail
cerulean elbow
slate swan
#
for file in os.listdir("../utils/cogs/"):
    if file.endswith(".py"):
        verify_command = client.load_extension(f'verify.{file[:-3]}')

this gives me error no module named "verify"

slate swan
#

layout

slate swan
#

its not verify.file it's in a f string

honest vessel
#

it is verify.{file[:-3]}

slate swan
#

yes

honest vessel
#

why

slate swan
#

it's in {}

narrow grail
slate swan
honest vessel
slate swan
#

the for loop looks for all the files in that directory i specified and then if the file endswith .py it will strip out the .py and load the file name

#

but i need to do it from my cwd

#

which is what im trying to figure out and i need help with it

honest vessel
#

@slate swanit should be like this

#
        for filename in os.listdir('./cogs'):
            filename.lower()
            if filename.endswith('.py'):
                filename = filename[:-3]
                if filename in botcogs:
                    try:
                        bot.load_extension(f"cogs.{filename}")
slate swan
#

but my cogs folder is not in the cwd

#

its in a previous directory

#

..

honest vessel
#

oh but it should still be cogs.filename

#

not vinity.filename?

slate swan
#

It should be verify and that’s all

#

So like ../utils/cogs/verify.py

honest vessel
#

@slate swancan u try change verify. to cogs. ?

#

on load_exstansion

slate swan
#

Ok I will try and return in 20 minutes I have to go out with my dog

honest vessel
#

lol

slate swan
#

But thanks for the help.

honest vessel
#

it takes 1 second but whatever

cosmic agate
#

hwy guys

#

i made meme command with button

#

but button not giving new meme

#
  random_sub = random.choice(all_subs)

  name = random_sub.title
  url = random_sub.url
  likes = random_sub.score
  comments = random_sub.num_comments
  link = random_sub.selftext

  button = Button(label="Next Meme", style=nextcord.ButtonStyle.green)

  async def button_callback(interaction):
    await interaction.response.edit_message(nextcord.Embed(title = name, url = url, colour=nextcord.Colour.random()))

  button.callback = button_callback

  
  em = nextcord.Embed(title = name, url = url, colour=nextcord.Colour.random())
  button = Button(label="Next Meme", style=nextcord.ButtonStyle.green)

  async def button_callback(interaction):
    await interaction.response.edit_message(nextcord.Embed(title = name, url = url, colour=nextcord.Colour.random()))
  view = View()  
  view.add_item(button)
  em.set_image(url = url)
  em.set_footer(text =f"👍 {likes} | 💬 {comments}")

  await ctx.send(embed= em, view=view)
#

this my code

honest vessel
#

btw kek

cosmic agate
#

all code is not there, only important code

cerulean elbow
honest vessel
#

if button not give new meme its probally cause u dont recall the function that grabs memes

#

random.choice() only run once

#

when bot starts?

flat solstice
#

so per d.py's asycio changes I have this main func which starts my botpy async def main(self): async with aiohttp.ClientSession() as session:is there a way for me to access this ClientSession() elsewhere in my code (in one of my cogs)

cosmic agate
cosmic agate
honest vessel
#

I mean can u post code

#

u kinda cut off the code...

cosmic agate
#

no i remove code where theres confidential stuff

honest vessel
#

when is this runned ```py
random_sub = random.choice(all_subs)

name = random_sub.title
url = random_sub.url
likes = random_sub.score
comments = random_sub.num_comments
link = random_sub.selftext

button = Button(label="Next Meme", style=nextcord.ButtonStyle.green)

#

and how

cosmic agate
#

??

cerulean elbow
honest vessel
#

@cosmic agatei guess no one can help u then

cosmic agate
gaunt ice
#

what's the problem

honest vessel
#

cause u dont show code that is part of issue

cosmic agate
#
@bot.command(aliases = ['MEME', 'Meme', 'Memes', 'MEMES', 'memes'])
async def meme(ctx):
  all_subs = []


  subreddit = reddit.subreddit("meme")

  top = subreddit.top(limit = 50)

  for submission in top:
    all_subs.append(submission)

  random_sub = random.choice(all_subs)

  name = random_sub.title
  url = random_sub.url
  likes = random_sub.score
  comments = random_sub.num_comments
  link = random_sub.selftext

  
  em = nextcord.Embed(title = name, url = url, colour=nextcord.Colour.random())
  button = Button(label="Next Meme", style=nextcord.ButtonStyle.green)

  async def button_callback(interaction):
    await interaction.response.edit_message(embed = em)
  button.callback = button_callback
  view = View()  
  view.add_item(button)
  em.set_image(url = url)
  em.set_footer(text =f"👍 {likes} | 💬 {comments}")

  await ctx.send(embed= em, view=view)
honest vessel
#

as i thought ur code

cosmic agate
#

??

honest vessel
#
  random_sub = random.choice(all_subs)

  name = random_sub.title
  url = random_sub.url
  likes = random_sub.score
  comments = random_sub.num_comments
  link = random_sub.selftext
``` that gernerates memes is only ran once when so if u click buttons its same meme
cosmic agate
#

hmm

#

so how to make new meme?

honest vessel
#

u need to make random_sub = random.choice(all_subs)

#

run when click button

cosmic agate
#

explain

#

idu

honest vessel
#

simple way would be make a function that returns memes

#

and use that function on ur button too

cosmic agate
#

IDU

#

sorry for caps

#

could you explain

honest vessel
#

hmm

#

i thought i did 😛 but i will try agian

#

have a function that generates memes

#

let it return the data u want to use

#

and button_callback recall that function again

#

that way it will rerun the generate_meme function

cosmic agate
#

im sorry im dumb

#

ill be back

honest vessel
#

lol?

#
my_function():
     return random.randint(0,10)

print(my_function())
print(my_function())
frozen elk
#

whats the use of "!r" python

honest vessel
#

!e
name="monkey"
string = f"{name!r}"
print(string)

#

no idea

honest vessel
#

so it sais same

slate swan
#

yes

honest vessel
#

did u import Cog?

slate swan
#

import cog?

manic wing
honest vessel
#

from discord.ext.commands import Cog

slate swan
#

this is the bot.py file which only should load it

#

idu

slate swan
honest vessel
#

i dont even know what idu means

slate swan
slate swan
manic wing
#

whelp

honest vessel
#

can u show ur imports

manic wing
honest vessel
#

prob forgot import Cog

honest vessel
proper acorn
#

Everyone

#

What is

honest vessel
#

42

proper acorn
#

'r' when read json file

honest vessel
#

it means read

manic wing
unkempt canyonBOT
#

Opening files

The built-in function open() is one of several ways to open files on your computer. It accepts many different parameters, so this tag will only go over two of them (file and mode). For more extensive documentation on all these parameters, consult the official documentation. The object returned from this function is a file object or stream, for which the full documentation can be found here.

See also:
!tags with for information on context managers
!tags pathlib for an alternative way of opening files
!tags seek for information on changing your position in a file

The file parameter

This should be a path-like object denoting the name or path (absolute or relative) to the file you want to open.

An absolute path is the full path from your root directory to the file you want to open. Generally this is the option you should choose so it doesn't matter what directory you're in when you execute your module.

See !tags relative-path for more information on relative paths.

The mode parameter

This is an optional string that specifies the mode in which the file should be opened. There's not enough room to discuss them all, but listed below are some of the more confusing modes.

'r+' Opens for reading and writing (file must already exist)
'w+' Opens for reading and writing and truncates (can create files)
'x' Creates file and opens for writing (file must not already exist)
'x+' Creates file and opens for reading and writing (file must not already exist)
'a+' Opens file for reading and writing at end of file (can create files)

proper acorn
#

oh ok tysm!

slate swan
# manic wing show code
import discord
import pathlib

from json import load
from discord import app_commands
from discord.ext import commands

with open("../config/config.json", "r") as f:
    config = load(f) 

intents = discord.Intents.all()

client = commands.Bot(command_prefix=None)


dir_name = "../utils/cogs"
cwd = pathlib.Path(__file__).parent
new_path = cwd / dir_name

path = pathlib.Path.iterdir(new_path).stem

@client.event
async def on_ready():
    print(f"Logged in as {client.user}\nID: {client.user.id}")
    await client.load_extension(path)
    await client.tree.sync()

client.run(config["token"])
manic wing
#

dude read the error

manic wing
honest vessel
#

yes am sorry am wrong lol

honest vessel
#

and dont load on on_ready plz

manic wing
# honest vessel yes am sorry am wrong lol

python errors say exactly where the error comes from, if there is some python folder in the file path then you know the error is coming from the internals, meaning they passed an arg wrong, not imported something wrong

forest minnow
#

how to make code for all members counting on all servers where is bot?

honest vessel
#

@slate swandont load exstentions in on_ready
and consider have a loop for more files u wanna load in future

honest vessel
#
        total_users = 0
        total_bots = 0
        for x in self.bot.guilds:
            for y in x.members:
                if y.bot:
                    total_bots += 1
                else:
                    total_users += 1 
``` ?
forest minnow
#

counting in status or in command

honest vessel
forest minnow
#

example: 1000 members

#

on 20 servers

honest vessel
#

@manic wingtheory is same tho

forest minnow
#

all members in all servers count

honest vessel
#

u can grab how many servers with len(bot.guilds)

slate swan
#

you do know that the whole web works on json (mostly)

cosmic agate
#

ik

honest vessel
#

json is crap for using as database thats all

cosmic agate
honest vessel
#

database -> json is the way

slate swan
cosmic agate
slate swan
#

json isnt bad ;-;

honest vessel
#

json is good if used correctly

slate swan
#

nor does it have anything to do with discord

cosmic agate
cosmic agate
vocal plover
#

using json correctly is very very simple: use it for data transmission

honest vessel
#

i mean if u want to call alot json is tiny n fast... cache from database give json to be used/spammed

#

instead of call database

cosmic agate
#

hmm

#

so

honest vessel
#

or to share data like api json is the way

slate swan
#

json isnt a database, its a data type, how dows SQL even come in the way of json

honest vessel
#

json != database

#

yeah

slate swan
#

json is for formatting data

#

dunno who put that in people's head

honest vessel
#

discord bots put in their heads

#

economic bots kek

slate swan
#

no j's son😳

slate swan
honest vessel
slate swan
honest vessel
#

and has a very small server

#

but think json is for store DATA as a database ur so wrong

slate swan
#

anyways, its ot lol

honest vessel
#

what i am saying

#

u just say same thing diffrent words

cosmic agate
#

ddddd

slate swan
#

@cosmic agate so, yes, use that, endpoint, it'll save power and be faster

honest vessel
#

json is a static file it is nothing more than a textfile

slate swan
#

^^

slate swan
honest vessel
#

But yeah just learn to use a databse

cosmic agate
#

i dont want to complicate things for a meme command

honest vessel
#

@cosmic agatedid u do as i said?

cosmic agate
#

also idk about OOP

honest vessel
#

make ur meme_generator as a function

cosmic agate
honest vessel
#

and call that function for ur button n when use command

slate swan
honest vessel
#

^lol

#

@cosmic agatebasic python tho, play around with functions so u know how u can call em

#

or as they call it methods

lusty sky
#

What permission attribute is for unbanning
does ban_members give permission to unban also?

regal cove
#

i use an sqlite database for my discord bot and i wonder if i can make a command which will register everysingle member in a discord server and save their information (id and balance) in my db file? would i have to make a loop which registers them all or can i just get the member list and get them all?

lusty sky
#

but not all who have perms to ban also have admin

vocal plover
#

Please don't give admin to bots for that - yes ban_members also lets you unban

lusty sky
lusty sky
honest vessel
#

@cosmic agatei give u one more example of functions so u understand

import random

def number_generator():
    generated_number = random.randint(0, 100)
    return generated_number


a = number_generator()
b = number_generator()

``` a and b gonna call number_generator() and get a number
regal cove
vocal plover
#

Please stop giving potentially dangerous advice

honest vessel
#

sketchy link

regal cove
#

just no. its not dangerous at all

lusty sky
regal cove
#

just dont test commands in a server u cant risk stuff in

vocal plover
regal cove
#

how would just token get leaked?

#

just dont be stupid and it wont get leaked dude

vocal plover
#

You didn't read the page lmao

#

because it explains in response to exactly that

final iron
#

^

#

🗿

honest vessel
#

dont invite a bot someone tells u to invite

regal cove
honest vessel
#

and u safe

regal cove
#

how would u possibly leak your token tho

regal cove
honest vessel
#

oh fuck no

final iron
honest vessel
#

my bot is server-owner

lusty sky
#
@kick.error
async def kick_error(error, ctx):
    if isinstance(error, MissingPermissions):
        text = "Sorry {}, you do not have permissions to do that!".format(ctx.message.author)
        await ctx.send_message(ctx.message.channel, text)```
regal cove
lusty sky
#

any reason why it doesnt say this when someone cant use the command?

regal cove
#

and i dont see how a person could leak your token

#

imo that article is just wrong in so many ways

vocal plover
#

You could leak your own token, humans make mistakes, as the page explains

final iron
regal cove
#

would u test commands in a server u care about

regal cove
#

just keep your token for yourself and no one will get it

vocal plover
#

So you've never done anything by accident before which you regretted?

final iron
#

^

regal cove
#

just like u wouldnt tell anyone your password u wouldnt tell anyone your token

lusty sky
final iron
vocal plover
final iron
#

ctx will be interpreted as the error and error will be interpreted as context

vocal plover
#

so just because you wouldnt tell anyone doesnt mean it cant get leaked

regal cove
#

but ur acting like thats cus someone told them their password

honest vessel
#

@lusty skywhen u place error, ctx u kinda twist them

regal cove
slate swan
cosmic agate
lusty sky
#

giving bot admin

honest vessel
regal cove
#

they are saying u shouldnt give your admin perms

#

and maybe u shouldnt but i dont agree with the arguments they said

lusty sky
vocal plover
#

those points have been pinned in this channel for the best part of a year now with no complaints from anyone else

slate swan
regal cove
#

alright

#

honestly tho this is a useless argument guys

honest vessel
#

@slate swanpost cute emojis

regal cove
#

it really doesnt matter

slate swan
honest vessel
#

jk lol

regal cove
#

if u guys wont give admin perms to your bots thats fine

#

just kick and reinvite your bot if thats needed

honest vessel
#

I would never invite a public bot asking for admin persm thats for sure tho

regal cove
#

and if my bot gets fucked cus i leaked my token i will tell u guys and u can all laugh at me

regal cove
#

ik

#

but im just trying to end the argument cus it really doesnt matter lol

#

it such a small detail honestly

honest vessel
#

CTRL+SHIFT+i copy the weird line of random numbers n letters ty @slate swan

full lily
#

This might be true for bots, but I'm not so sure about user accounts

slate swan
vocal plover
cosmic agate
regal cove
#

all y'all smart people can also go to #databases and help me out with my discord bots database there thank u very much

vocal plover
#

@unkempt canyon will delete your message but the token is still valid, neither Discord not the pydis bots will revoke your token if posted in chat

#

Yes

#

I said that discord wont revoke the token

#

It's possible someone uploaded it to github to get it changed, but Discord doesnt actively scan messages for tokens and revoke the tokens, it will display a popup if you try to send tokens now, but no backend automation exists right now to reset them

slate swan
#
numbers = list(range(1,100))

@bot.command(alises = ["si"])
async def simp(ctx):
  ctx.send("You are " + random.choice(numbers) + "% simp")
cosmic agate
#

sad

slim ibex
#

string cant be added to int

slate swan
#

ohhhhhhhh

#

random.randint()

cold sonnet
#

and f-strings and await

velvet tinsel
cold sonnet
#

he made a typo on aliases

velvet tinsel
#

yeah I figured

cold sonnet
#

but he can use simp too

velvet tinsel
#

i was wondering why he didn't get an error about that

hushed galleon
#

i know RoboDanny on the discord.py server automatically uploads tokens to github for discord's system to see

velvet tinsel
slate swan
velvet tinsel
cold sonnet
#

robodanny literally has access to everything

velvet tinsel
#

random.randint(<number, <number>)

slate swan
#

omg

#

im dumb as fuc

velvet tinsel
#

🤷

cold sonnet
#

did they really name the argument b

velvet tinsel
#

yes

slate swan
velvet tinsel
#

!d random.randint

unkempt canyonBOT
#

random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
cold sonnet
#

ew

velvet tinsel
cold sonnet
#

you sound really briish there mate

slate swan
#

do i have to put ><

cosmic agate
#

guys i made a meme command

slate swan
velvet tinsel
cold sonnet
cosmic agate
slate swan
slate swan
cosmic agate
#

but the button doesnt work

#
@bot.command(aliases = ['MEME', 'Meme', 'Memes', 'MEMES', 'memes'])
async def meme(ctx):
  all_subs = []


  subreddit = reddit.subreddit("meme")

  top = subreddit.top(limit = 50)

  for submission in top:
    all_subs.append(submission)

  random_sub = random.choice(all_subs)

  name = random_sub.title
  url = random_sub.url
  likes = random_sub.score
  comments = random_sub.num_comments
  link = random_sub.selftext

  
  em = nextcord.Embed(title = name, url = url, colour=nextcord.Colour.random())
  button = Button(label="Next Meme", style=nextcord.ButtonStyle.green)

  async def button_callback(interaction):
    await interaction.response.edit_message(embed = em)
  button.callback = button_callback
  view = View()  
  view.add_item(button)
  em.set_image(url = url)
  em.set_footer(text =f"👍 {likes} | 💬 {comments}")

  await ctx.send(embed= em, view=view)

velvet tinsel
slate swan
cold sonnet
#

I started being proud of you transil

#

ey what for those frankly many variables

#

DEKRIEL I'M LIKE U

lusty sky
#

The user has no perms to manage_messages and I have a permission check for it to use the clear command but for some reason they can still make the bot clear messages?

#

Any idea why?

#
@client.command()
@commands.has_permissions(manage_messages=True)
async def clear(ctx, amount=30):
    await ctx.channel.purge(limit=amount+1)```
cold sonnet
#

seems right to me

#

but amount isn't an int

slate swan
#
@bot.command(alises = ["si"])
async def simp(ctx):
  ctx.send("You are " + random. randint(1,101) + "% simp")
#

bRIJ

slate swan
cold sonnet
#

convert it to an str

slate swan
#

OHHH nvm

velvet tinsel
#

use f-strings or just convert it to a str mate

cold sonnet
#

mate

velvet tinsel
#

is it late there?

terse blade
cold sonnet
#

!d discord.Intents

unkempt canyonBOT
#

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

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

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

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

New in version 1.5...
lusty sky
lusty sky
cold sonnet
#

huh

slate swan
#

why this code not working???

@bot.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, user: discord.Member, *, reason=None):
    if not reason:
        await user.ban()
        await ctx.send(f"**{user}** has been banned for **no reason**.")
    else:
        await user.kick(reason=reason)
        await ctx.send(f"**{user}** has been banned for **{reason}**.")
slate swan
velvet tinsel
#

also why did you use user.kick lmao

#

I thought it was a ban command

slate swan
#

can anyone give me am example of how this f in string thingy works

cold sonnet
#

could remove the whole check for the reason

boreal ravine
#

!f-strings

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

velvet tinsel
#

they have an s at the end which is fucking annoying

slate swan
boreal ravine
#

import it..

velvet tinsel
cold sonnet
#

import what

slate swan
velvet tinsel
#

@boreal ravine i dont think they forgot to import it though

#

it would have an attribute error

terse blade
#

what is blue?

velvet tinsel
#

or if they just used randint() then perhaps

velvet tinsel
terse blade
cold sonnet
velvet tinsel
#

*colour

unkempt canyonBOT
#

classmethod blue()```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/master/api.html#discord.Colour "discord.Colour") with a value of `0x3498db`.
velvet tinsel
terse blade
#

ty

cold sonnet
velvet tinsel
#

thanks

#

is danny briish or something lmao

slate swan
velvet tinsel
#

discord.Colour

cold sonnet
#

there's a Color one too

#

but that's just an alias

velvet tinsel
#

🤷

slate swan
#

Bog

velvet tinsel
slate swan
#

pog

velvet tinsel
#

yeah

cold sonnet
#

not listed on the docs either

slate swan
boreal ravine
#

not documented

boreal ravine
cold sonnet
#

how are u sure

slate swan
#

Yooo… Python… thoughts?

velvet tinsel
velvet tinsel
#

Mate this is discord-bots not python general

cosmic agate
#

with next meme button
but the button doesnt work

@bot.command(aliases = ['MEME', 'Meme', 'Memes', 'MEMES', 'memes'])
async def meme(ctx):
  all_subs = []


  subreddit = reddit.subreddit("meme")

  top = subreddit.top(limit = 50)

  for submission in top:
    all_subs.append(submission)

  random_sub = random.choice(all_subs)

  name = random_sub.title
  url = random_sub.url
  likes = random_sub.score
  comments = random_sub.num_comments
  link = random_sub.selftext

  
  em = nextcord.Embed(title = name, url = url, colour=nextcord.Colour.random())
  button = Button(label="Next Meme", style=nextcord.ButtonStyle.green)

  async def button_callback(interaction):
    await interaction.response.edit_message(embed = em)
  button.callback = button_callback
  view = View()  
  view.add_item(button)
  em.set_image(url = url)
  em.set_footer(text =f"👍 {likes} | 💬 {comments}")

  await ctx.send(embed= em, view=view)

velvet tinsel
slate swan
#

how to make your bot send embed?

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.

Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
velvet tinsel
#

Ah I see they have changed Embed.Empty

cosmic agate
#

??

honest vessel
#

type='poor'?

slate swan
velvet tinsel
#

check this out, I looked on the docs

#

'rich' apparently means " generic embed rendered from embed attributes"

#

i don't like it when kayle types it makes me nervous

boreal ravine
#

just checked, he's from SA, just thought he was japanese because he speaks it lol

pallid meadow
slate swan
#
ctx.send(f'You are ' {random.randint(1,101)} '% simp') 
boreal ravine
slate swan
#

wil it work

boreal ravine
#

no

slate swan
#

why D:

boreal ravine
slate swan
#

what did i doo wrong this time

slate swan
#

i'm working on a discord bot that checks a api for it's contents, but if it hasn't found anything (the api) it just returns {"success":"error"} but if it has it returns {"found":"12"} but if i have foundamount = data['found'] in the same discord command it bugs out when it doesnt find anything. im trying to find out a way to check first if it hasnt found anything and if it has to open a def function that sneds the text of the found things.

#

like that?

boreal ravine
cosmic agate
boreal ravine
# cosmic agate wdym

!d nextcord.InteractionResponse.defer if you don't send anything in the interaction within 3 seconds, you have to defer it

unkempt canyonBOT
#

await defer(*, ephemeral=False, with_message=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.
boreal ravine
#

use that method at the top of the method by the way

boreal ravine
#

it does though

#

what don't you get?

boreal ravine
slate swan
#

I've tried opening a function but it never works

#

Could u give me an example?

boreal ravine
terse blade
#

how to slash commands

slate swan
boreal ravine
slate swan
#

OHH

boreal ravine
slate swan
#

wait lemme try

#

if it doesnt work ill lyk

slate swan
boreal ravine
#

Ok

glossy hill
#

hello