#discord-bots

1 messages · Page 1082 of 1

frozen patio
#

Alright so I am trying to ping the user at the top when they win, but when I do it in this code it gives an error that says 'list' has no attribute 'mention'.
How can I fix this?

sick birch
#

Should be winner instead of winners

scarlet sorrel
#

thats what it returns?

sick birch
#

An instance of it, yes

scarlet sorrel
#

wym instance

sick birch
#

An instance of a class

#

In this case, datetime.datetime

scarlet sorrel
#

so to get a date i should do discord.utils.snowflake_time(id).datetime ?

sick birch
#

It returns a datetime.datetime by default, you don't have to call .datetime on it again

frozen patio
sick birch
frozen patio
#

Well it all worked, until I wanted to add where it pings the winner

#

I am just looking to ping the winner

frozen patio
#

And send that embed with it

sick birch
#

I know what you're trying to do with it, can you print winner and winners though?

#

Something strange might be going on

cursive barn
#

you don't need to print winner - the traceback says its a list. so you must find where you declare it and ensure you haven't done so by initiating a list. perhaps by sending your full code we can assist more @frozen patio

frozen patio
#

Alright

frozen patio
#

Let me know what I am doing wrong

sick birch
#

looks like you're using winner = random.choices() so it's going to return a list

frozen patio
#

Oh

sick birch
#

I'm not sure why you have both winner and winners though

frozen patio
#

Ok, well, how can I just ping the winner

sick birch
#

There are multiple, which do you want to ping?

frozen patio
#

The winner whom won the giveaway

lyric apex
sick birch
#

It looks like your code allows for multiple winners however

frozen patio
#

Yes

sick birch
#

So, you want to ping all of them?

frozen patio
#

Yes the winner(s) of the giveaway

lyric apex
sick birch
#

' '.join([winner.mention for winner in winners])

#

You need to sort out winner/winners in your code first

lyric apex
sick birch
lyric apex
sick birch
#

Then it's probably not in your bot's cache, which case you can try to use fetch_channel

lyric apex
#

ohk lemmie try that

cursive barn
#

so first, you have a table value set here: py time, prize, message, channel, guild, participants, winners, finished = table[0], table[1], table[2], table[3], table[4], table[5], table[6], table[7]
and then later you overwrite that with py winners = []
I would recommend some object naming clarification with that.

Secondly, I would recommend condensing lines 68-74 into a list comp, something like py winner = [guild.get_member(int(user)).name for user in random.choices(participants, k=len(participants)] or k=winners depending on how many people are entered.

Thirdly, you need to use a string comp function to build your message when you send it, typically via the .join() function. ```py
message = f'Congrats to {", ".join([user.mention for user in winner])} for winning the giveaway'

sick birch
lyric apex
sick birch
#

I don't believe it has to be a kwarg

cursive barn
#

it is not afaik

smoky cedar
sick birch
#

Though positionals can be kwargs, so if you want to go right ahead

smoky cedar
#

Just updated the parameter name for my bots command and this

#

How can I refresh the servers commands?

sick birch
smoky cedar
sick birch
#

Ah, can't assist with discord_slash. Regular d.py I can do

#

Speaking of, discord.py has built in slash commands, consider migrating to those instead of frankly outdated libraries

lyric apex
#

@sick birch

#

This is comingQtpie

frozen patio
#

I thought it would be simple just to make a simple ping

cursive barn
#

my third suggestion solves your ping issue. the first two are simply pieces of advice from 20+ years of coding experience

frozen patio
#

So I need to put message = inside of the send function

cursive barn
#

no

#

you need to declare your message following the format i used

#

you tried to call .mention on the whole list rather than the items in the list, which is solved by nesting a list comp of user.mention inside of a .join method

frozen patio
# cursive barn you need to declare your message following the format i used

I got this error with your fix:

Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/nextcord/ext/tasks/__init__.py", line 168, in _loop
    await self.coro(*args, **kwargs)
  File "/home/container/cogs/giveaway.py", line 77, in giveawayCheck
    message = f'{", ".join([user.mention for user in winner])}'
  File "/home/container/cogs/giveaway.py", line 77, in <listcomp>
    message = f'{", ".join([user.mention for user in winner])}'
AttributeError: 'int' object has no attribute 'mention'
visual island
#

user seems to be an int

frozen patio
#

That might be the ID

#

Yep it is

#

You can't do str element here either

slate swan
#

is there anyway to add an attachment to an embed by a link?

slate swan
pulsar bay
#
    @commands.Cog.listener()
    async def on_member_ban(self, guild, user):
        reason = "Anti-Nuke | Banning Members"
        whitelisted = db.find_one({ "guild_id": guild.id })['whitelisted-users']
        async for i in guild.audit_logs(action=AuditLogAction.ban):
   
            if i.user.top_role >= guild.me.top_role:
                return
 
            if i.user.id not in whitelisted:
                await guild.ban(i.user, reason=f'{reason}')
2022-06-03T00:49:52.188846+00:00 app[worker.1]:   File "/app/cogs/antievents.py", line 20, in on_member_ban
2022-06-03T00:49:52.188846+00:00 app[worker.1]:     if i.user.top_role >= guild.me.top_role:
2022-06-03T00:49:52.188883+00:00 app[worker.1]: AttributeError: 'User' object has no attribute 'top_role'

Any help?

frozen patio
# slate swan just do ```py [f"<@{user}>" for user in winner] ```

Uhhhhh That worked 1 time

Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/nextcord/ext/tasks/__init__.py", line 168, in _loop
    await self.coro(*args, **kwargs)
  File "/home/container/cogs/giveaway.py", line 80, in giveawayCheck
    msg = await channel.fetch_message(message)
  File "/home/container/.local/lib/python3.10/site-packages/nextcord/abc.py", line 1513, in fetch_message
    data = await self._state.http.get_message(channel.id, id)
  File "/home/container/.local/lib/python3.10/site-packages/nextcord/http.py", line 337, in request
    raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In message_id: Value "Congrats @frozen patio!" is not snowflake.
slate swan
pulsar bay
slate swan
frozen patio
#

the ID is an int

frozen patio
cursive barn
#

remove the .name part of your winner selection list comprehension @frozen patio

slate swan
slate swan
pulsar bay
#

i have that already check my code

slate swan
#

@pulsar bay were you trying to do that comand on a bot?

frozen patio
#

No matter how many people entered

slate swan
sick birch
#

discord.User is a model, it doesn't belong to anything

slate swan
#

@sick birch is there anyway to add an attachment to an embed by a link?

potent spear
#

!d discord.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`.
keen mural
#
class Fight3(discord.ui.View):
    def __init__(self, context: commands.Context):
        super().__init__(timeout=None)
        self.value = None
        self.command_ctx = context```
with my view, `timeout=None` works, but if i plug in an amount of seconds like 5 it instantly times out, anybody know what im doing wrong?
slate swan
pulsar bay
#

@sick birch

buoyant zodiac
#
async def setup(bot):
    await bot.add_cog(Server(bot))
``` "coroutine 'setup' was never awaited
  setup(self)"
shrewd apex
cursive barn
#

setup and bot.add_cog shouldn't be coroutines iirc

sick birch
#

I'm suspecting that they're on an older version but using the async version of setup, so d.py calls it w/o awaiting

buoyant zodiac
vital glacier
#

Anyone here that knows stuff about working with errors and commands.MissingRequiredArgument, getting them to send embeds from a different cog (help embeds)

#

Because rn I am trying this:

    @commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        ignored = (commands.CommandNotFound, commands.UserInputError)
        if isinstance(error, ignored):
            print(error)

        if isinstance(error, commands.CommandOnCooldown):
            m, s = divmod(error.retry_after, 60)
            h, m = divmod(m, 60)
            if int(h) == 0 and int(m) == 0:
                await ctx.send(
                    f' {ctx.author.mention}, you must wait **{int(s)}** seconds to use the **{ctx.invoked_with}** command!')
            elif int(h) == 0 and int(m) != 0:
                await ctx.send(
                    f' {ctx.author.mention}, you must wait **{int(m)} minutes** and **{int(s)} seconds** to use the **{ctx.invoked_with}** command!')
            else:
                await ctx.send(
                    f' {ctx.author.mention}, you must wait {int(h)} hours, {int(m)} minutes and {int(s)} seconds to use the **{ctx.invoked_with}** command!')
        elif isinstance(error, commands.MissingPermissions):
            missing = [perm.replace('_', ' ').replace('guild', 'server').title() for perm in error.missing_permissions]
            if len(missing) > 2:
                fmt = '{}, {}'.format(", ".join(missing[:-1]), missing[-1].lower())
            else:
                fmt = ' and '.join(missing)
            _message = '{}: **{}** requires the `{}` permissions'.format(ctx.author.mention, ctx.invoked_with,
                                                                         fmt.lower())
            e = discord.Embed(
                description=f'{_message}',
                color=0xf8a424
            )
            await ctx.send(embed=e)
        elif isinstance(error, commands.MissingRequiredArgument):
            return Help.send_command_help()
        return error

but the last elif isinstance won't work and I can't seem to figure out how I can fix it

sick birch
#

You call .send_command_help() on the bot instance iirc

slate swan
#

!d discord.ext.commands.Context.send_help

unkempt canyonBOT
#

await send_help(entity=<bot>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Shows the help command for the specified entity if given. The entity can be a command or a cog.

If no entity is given, then it’ll show help for the entire bot.

If the entity is a string, then it looks up whether it’s a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog") or a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command").

Note

Due to the way this function works, instead of returning something similar to [`command_not_found()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HelpCommand.command_not_found "discord.ext.commands.HelpCommand.command_not_found") this returns `None` on bad input or no help command.
buoyant zodiac
#

can anyone help me install stuff thru python on linux

slate swan
#

python -m pip install <library>

keen talon
slate swan
#

not really

keen talon
#

Why not yert

slate swan
#

this is hosted on a linux server

keen talon
#

👀

stone beacon
#

I think that's because there are 2 versions of cpython

#

The 2.7.x and the 3.x.x

slate swan
buoyant zodiac
slate swan
slate swan
slate swan
slate swan
# slate swan why not?

the api im using for a seperate command has a bug and if it's not an attachment it wont send as a gif.

#

may i see ur code

slate swan
#
@client.command()
async def pet(ctx, *, user: discord.Member = None):
  embed = discord.Embed(title=f"Pet!", color=discord.Color.blue())
  av = str(user.avatar_url)
  replace = av.replace("webp", "png")
  embed.set_image(url="https://api.popcat.xyz/pet?image={}".format(replace))
  await ctx.send(embed=embed)
buoyant zodiac
slate swan
#

you can use aiohttp to read the bytes of the image @slate swan and then send it as a local attachment

#

!local-file

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
slate swan
buoyant zodiac
#

i do

slate swan
slate swan
slate swan
slate swan
unkempt canyonBOT
#

class io.BytesIO(initial_bytes=b'')```
A binary stream using an in-memory bytes buffer. It inherits [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase"). The buffer is discarded when the [`close()`](https://docs.python.org/3/library/io.html#io.IOBase.close "io.IOBase.close") method is called.

The optional argument *initial\_bytes* is a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) that contains initial data.

[`BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO "io.BytesIO") provides or overrides these methods in addition to those from [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase") and [`IOBase`](https://docs.python.org/3/library/io.html#io.IOBase "io.IOBase"):
slate swan
#

would it be like request json or text?

#

I dont get it

slate swan
# slate swan I dont get it
  1. make a request to the image url py res = await session.get("url")
  2. then read the response
byte_data = await res.read()
``` where `session` is an aiohttp.ClientSession
keen mural
slate swan
#

nice bug

maiden fable
keen mural
slate swan
#

huh? thats latest and not even released

oak warren
#

and added it in on ready ?

#

for persistent

slate swan
#
async def setup_hook(self) -> None:
     await self.load_extension(ExampleCog(self))

why does this raise

AttributeError: 'ExampleCog' object has no attribute 'startswith'
slate swan
shrewd apex
#

seems like an error in the cog to me

slate swan
#

or used any instance

slate swan
shrewd apex
#

in ur cog i suppose...

slate swan
#

youre supposed to pass a string

#

wdym

#

oh wait nvm

#

just ignore

#

im dying

shrewd apex
#

👍

slate swan
#

the attr error got raised because you passed an object into Bot.load_extension

paper sluice
wary mist
#

&6hi

dim ruinBOT
#
Command not found

Command "6hi" is not found

slate swan
#

imagine handling CommandNotFound errors

alpine pewter
#
@bot.slash_command(guild_ids=guild_ids, description="Get your token!")
async def get_token(interaction : Interaction):
    global nitrado_api_key
    client_guild_name = interaction.guild.name

    reference = db.reference(f"/")
    value = reference.child(client_guild_name).get()
    server_key = value["client_token"]

nitrado_api_key = server_key #Issue Here

bot.run(config.api_key)

If I want to save the last variable server_key as nitrado_api_key in a "global" variable, would this be how or am I misunderstanding what the global means?

paper sluice
maiden fable
#

Ngl those and MissingPermissions errors are the most common ones @slate swan

dusky pine
#

don't send any embeds or messages

#

that's just dumb

paper sluice
#

so //

dusky pine
paper sluice
#

fuck me, im high, yea ill go sleep

dusky pine
#

oh LOL

alpine pewter
#

Uhhh

#

I'm confused, where would that even go?

paper sluice
dusky pine
maiden fable
dusky pine
#
@bot.slash_command(guild_ids=guild_ids, description="Get your token!")
async def get_token(interaction : Interaction):
    global nitrado_api_key
    client_guild_name = interaction.guild.name

    reference = db.reference(f"/")
    value = reference.child(client_guild_name).get()
    server_key = value["client_token"]

    nitrado_api_key = server_key #This line should have one indent (which I already did, no need)
slate swan
alpine pewter
#

So, I think I misunderstand the global then.
I'm wondering, how would I use that same variable in another command or is that not possible?

alpine pewter
#

Or, is that actually all I need to do for that

dusky pine
#

you're using global correctly

#

yes

alpine pewter
#

Okay, let me try it in another, thank you ^^

slate swan
#

!botvar

unkempt canyonBOT
#

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

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

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

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

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

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

dusky pine
#

or just subclass Bot and add your own

#

i don't like botvars because intellisense 😔

paper sluice
slate swan
#

well, it appears for me on autocompletes

dusky pine
#

lmao

#

luucky 😔

slate swan
#

🚶‍♂️wait, does it not for you? only in cogs maybe right?

dusky pine
#

yeah I use cogs

#

it doesn't autocomplete self.bot.<botvar>

slate swan
dusky pine
#

yes i did

#

talking about botvars

slate swan
#

ah maybe it doesnt work for vanilla initialising of classes

alpine pewter
#
@bot.slash_command(guild_ids=guild_ids, description="Get your token!")
async def get_token(interaction : Interaction):
    global nitrado_api_key
    client_guild_name = interaction.guild.name

    reference = db.reference(f"/")
    value = reference.child(client_guild_name).get()
    server_key = value["client_token"]
    print(server_key)

    nitrado_api_key = server_key

@bot.slash_command(guild_ids=guild_ids)
async def test(interaction : Interaction):
    print(nitrado_api_key)

So, the bottom CMD should work fine then, right?
Figured to ask before I go test 😄

#

I've never used global

slate swan
#

if you invoke get_token first, and then test, it should work

alpine pewter
#

Got it, that's the goal.
Thank you ^^

slate swan
#

make sure to slide up in the terminal because it may get spammed with an error since you're not creating any response for the test command

alpine pewter
#

Will do, I'm very new to databases and am just trying to get it to work.
Thanks for the help 😄

nocturne phoenix
#

!docs

unkempt canyonBOT
nocturne phoenix
#

!numpy

dusky pine
#

!docs numpy

unkempt canyonBOT
#
nocturne phoenix
#

nvm you need to tap it

lyric apex
#

How to replace (),

slate swan
lyric apex
slate swan
#

pWut elaborate

lyric apex
slate swan
#

it a tuple

#

so use

slate swan
#

*d, where i'm assuming d is your tuple

#

yoru pWut

#

💀

#

!e ```py
print((1,)[0])

unkempt canyonBOT
#

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

1
lyric apex
#

Didn't get that Qtpie

lyric apex
slate swan
#

!e

s = "test",
print(type(s))
print(*s)
unkempt canyonBOT
#

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

001 | <class 'tuple'>
002 | test
slate swan
#

@lyric apex ^

lyric apex
#

Lemmie tryQtpie

slate swan
#

if u get it fine.. otherwise go with what sarth suggested, both are fine

#

💀 man my keybaord wtf

slate swan
lyric apex
slate swan
slate swan
#

me comparing myself with my young self

#

💀

#

no comments

lyric apex
slate swan
#

you prob did *(type(tuple))

#

whatever, at least show code along with error

lyric apex
#

I fixed leave itQtpie

slate swan
#

....

lyric apex
boreal ravine
robust fulcrum
#

Guys how we can take image as input in dpy 2.0?

alpine pewter
#

Would it be possible for someone to click a button and it pulls up a modal? I’m a bit unfamiliar with them. Just thought to ask.

paper sluice
paper sluice
alpine pewter
robust fulcrum
paper sluice
slate swan
#

its very possible, you just gotta send the Modal as the response to button click

shrewd apex
vital glacier
#

If I want to add a new random number to an already existing number in a sql database, how would I do that ( adding the new value to the old one and then updating it into the sql database)?

shrewd apex
vital glacier
#

rn im doing this, but this dont seem to work correctly:

    @commands.command()
    async def random(self, ctx):
        value = random.randint(1, 11)
        newvalue = value + value
        db = sqlite3.connect('astral.db')
        cursor = db.cursor()
        cursor.execute('SELECT value FROM test WHERE user_id = ?', (ctx.author.id,))
        data = cursor.fetchone()
        if not data:
            cursor.execute('INSERT INTO test(value, user_id) VALUES (?, ?)', (value, ctx.author.id))
            await ctx.send(f'added {value} to db. the value in the db is now {data}')
        if data:
            cursor.execute('UPDATE test SET value = ? WHERE user_id = ?', (newvalue, ctx.author.id))
            await ctx.send(f'added {value} to ur old value. value is now set to {data}')
        db.commit()
        cursor.close()
        db.close()
shrewd apex
#

newvalue here is doing value + value which u are updating later

#

so ur first step should be to fetch the old value and then add value to that

#

updating newvalue here will only update 2*random.randint(1,11)

#

so u should be updating data+value

vital glacier
#

ah

shrewd apex
#

also sqlite 3 here is sync while discord commands are asynchronous so this will limit this command to only one person use at one time

shrewd apex
#

multiple people will not be able to use this command

vital glacier
#

they will?

shrewd apex
#

at the same time

vital glacier
#

how do i make it so that they will be able to use the cmds at the same time then

#

with the sql db

shrewd apex
#

u may not notice now with with few people testing rn and such low usage of db the task just gets over done fast when there are more people it will lag

vital glacier
#

aiosqlite?

#

yeah fair, gotta see how that works then with the whole connecting part

shrewd apex
#

yeah

vital glacier
#

because i tried that before but it was giving me trouble with doing stuff

#

as in connecting etc, which made no sense

shrewd apex
#

welp u can ask here or #databases if u run into any problems

paper sluice
#

:<

lyric apex
#

Can we check an content for ex if that endswith Xyz

paper sluice
#

ya?

#

just do if message.endswith('Xyz') in ur on_message event

lyric apex
#

That does not work in @paper sluice client wait for event?

paper sluice
#

ya it should?

loud pulsar
#

yo what is ctx?

lyric apex
loud pulsar
#

k

#

thx

robust fulcrum
#

@paper sluice if i take
async def filter(self, ctx, filter:str , image):

How can I load the image?

loud pulsar
#

yo do anyone know how can i access a .json file in replit

unkempt canyonBOT
#

open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)```
Open *file* and return a corresponding [file object](https://docs.python.org/3/glossary.html#term-file-object). If the file cannot be opened, an [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") is raised. See [Reading and Writing Files](https://docs.python.org/3/tutorial/inputoutput.html#tut-files) for more examples of how to use this function.

*file* is a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object) giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed unless *closefd* is set to `False`.)
lyric apex
#

Read Qtpie

loud pulsar
#

lets see

maiden fable
unkempt canyonBOT
#

json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)```
Deserialize *fp* (a `.read()`-supporting [text file](https://docs.python.org/3/glossary.html#term-text-file) or [binary file](https://docs.python.org/3/glossary.html#term-binary-file) containing a JSON document) to a Python object using this [conversion table](https://docs.python.org/3/library/json.html#json-to-py-table).

*object\_hook* is an optional function that will be called with the result of any object literal decoded (a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict")). The return value of *object\_hook* will be used instead of the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict"). This feature can be used to implement custom decoders (e.g. [JSON-RPC](http://www.jsonrpc.org) class hinting).

*object\_pairs\_hook* is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of *object\_pairs\_hook* will be used instead of the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict"). This feature can be used to implement custom decoders. If *object\_hook* is also defined, the *object\_pairs\_hook* takes priority.
lyric apex
loud pulsar
#

k

slate swan
#

wtf why do this

#

!d discord.Message.attachments

unkempt canyonBOT
slate swan
#

!d discord.Attachment.read

unkempt canyonBOT
#

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

Retrieves the content of this attachment as a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)") object.

New in version 1.1.
paper sluice
#

👀

maiden fable
oblique adder
#

Is there any github repo which is using aiomysql and nextcord for discord bot ? I just really need an example so anything is fine. I just couldn't find any

shrewd apex
#

you could find repos which have both examples and combine them to use search for a repo with nextcord and another with aiomysql

oblique adder
shrewd apex
oblique adder
#

It sound dumb right 😂

shrewd apex
#

what do u not know? how to connect?

#

or which part u need help with

oblique adder
#

like the aiomysql need loop as its args right ? idk what to pass in that

shrewd apex
#

ok have u subclassed ur bot class?

oblique adder
#

no

shrewd apex
#
async def conn():
    pool = await aiomysql.create_pool()
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
             bot.db = cur

async def main():
    async with bot:
       loop = asyncio.get_event_loop()
       loop.run_until_complete(test_example())
       bot.start(token)
syncio.run(main())
#

this is how u do in dpy 2.0

oblique adder
#

should be similar to nextcord right ?

shrewd apex
#

now u can access the cursor using bot.db

shrewd apex
#

i havent used aiomysql so there might be a few discrepancies but it should be roughly the same

oblique adder
#

Its ok this should be more than enough for me to continue

#

thanks

shrewd apex
vale wing
tulip matrix
#

anyone know to access the discord.py docs and acc find the stuff ur looking for

#

bc its so confusing

vale wing
#

You mean like !d command?

oblique adder
shrewd apex
vale wing
shrewd apex
vale wing
#

Still wtf is async with bot

shrewd apex
vale wing
#

!d help

tulip matrix
#

ah ok

vale wing
#

No I didn't mean use help builtin lmao

#

You actually need to make API requests to readthedocs

paper sluice
#

u can do other initlization stuff under that

vale wing
#

Didn't know it has aenter

maiden fable
#

U do know this isn't a general chat channel or smth and those GIFs suit better in general chats, right? (No offense meant)

maiden fable
#

Thanks for understanding

slate swan
#

my bot doesn't respond to any commands

#

no errors either

#

it runs bit it doesn't respond

#

@vale wing hmu if u can help

vale wing
#

And messages intent at all

maiden fable
#

ngl message content intent is a pain and now literally every person who is not well versed with the new discord api changes is gonna have the same. fucking. problem.

vale wing
#

Yes I gotta rewrite a huge bot to slash commands 🥲

#

I tried to scam discord for message content intent but failed

maiden fable
#

Not me, I already got access to those and members intent

vale wing
#

If I find the conversation I will show you

slate swan
vale wing
oblique adder
vale wing
maiden fable
vale wing
#

Ikr

maiden fable
#

What use case did u specify

visual island
woven bane
#

How do i stop replit from auto updating my modules?or is this something beyond the scope of the channel?

maiden fable
#

Hi there icy Cirno

visual island
#

Hi hunter

paper sluice
woven bane
#

Oh ok

robust fulcrum
#

How can we send dm in dpy 2.0?

maiden fable
#

!d discord.Member.send

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

Sends a message to the destination with the content given.

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

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

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

Do i need to define member ig?

maiden fable
maiden fable
unkempt canyonBOT
#

get_member(user_id, /)```
Returns a member with the given ID.

Changed in version 2.0: `user_id` parameter is now positional-only.
visual island
maiden fable
#

Lmao seems like u only changed yr name

visual island
maiden fable
#

Yea I was right

slate swan
#

@vale wing can u dm me how to do that intents

oblique adder
# vale wing ```py class MyBot(commands.Bot): async def setup_hook(self): ... # ...
async def conn(loop):
    pool = await aiomysql.create_pool(host='127.0.0.1', port=3306,
                                      user='root', password='',
                                      db='react', loop=loop)
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            React.db = cur

class MyBot(commands.Bot):
    async def setup_hook(self):
        loop = get_event_loop()
        loop.run_until_complete(conn(loop))
      
bot = MyBot(
    command_prefix=config.Bot_prefix,
    case_insensitive=True,
    help_command=None,
    intents=intent,
    strip_after_prefix=True,
)
...
bot.run(token)``` like this ?
paper sluice
robust fulcrum
#
import discord
from discord.ext import commands
import asyncio

class Select(discord.ui.Select):
    def __init__(self):
        options=[
            discord.SelectOption(label="Send!",emoji="✍🏻",description="Send the suggestion!"),
            discord.SelectOption(label="Cancel!",emoji="❌",description="Cancel the suggestion!")
            ]
        super().__init__(placeholder="Select an option",max_values=1,min_values=1,options=options)
    async def callback(self, interaction: discord.Interaction):
        if self.values[0] == "Send!":
            await interaction.response.send_message(content="successfully sent!",ephemeral=True)

class SelectView(discord.ui.View):
    def __init__(self, *, timeout = 180):
        super().__init__(timeout=timeout)
        self.add_item(Select())

class suggest(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        
    @commands.command()
    async def dm(self, ctx,user:discord.Member = None ):
        def check(msg):
            return msg.author.id == ctx.author.id and msg.channel.id == ctx.channel.id
        await ctx.send("**Send the message you want to send **",delete_after=5)
        mes = await self.bot.wait_for('message', check=check,timeout=20)
        mes = (mes.content)
        await ctx.send(f"This is your message:**{mes}** -\/ select the option below", view=SelectView(),delete_after=5)
        


async def setup(bot):
	await bot.add_cog(suggest(bot))

I made a command to send a dm
I want that when someone select send option from dropdown it sends dm
So where I have to put bot.send_message()?

robust fulcrum
#

No

paper sluice
slate swan
#

discord.py-self

robust fulcrum
#

Sorry

maiden fable
robust fulcrum
slate swan
paper sluice
unkempt canyonBOT
#

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

slate swan
#

i don't care

robust fulcrum
slate swan
maiden fable
#

Let's not talk about the lib here please, thanks

slate swan
robust fulcrum
maiden fable
#

What the

slate swan
robust fulcrum
#

I would recommend dpy or pycord

maiden fable
slate swan
#

BRO ITS THE SAME SOURCE, ITS JUST A FORK THAT ALLOWS TO LOG INTO USER TOKENS

robust fulcrum
robust fulcrum
maiden fable
#

<@&831776746206265384> might be able to help us with the situation here

west escarp
#

Take a deep breath, please

visual island
# slate swan BRO ITS THE SAME SOURCE, ITS JUST A FORK THAT ALLOWS TO LOG INTO USER TOKENS

However, a number of things have been removed. For example:

Intents: While the gateway technically accepts Intents for user accounts (and even modifies payloads to be a little more like bot payloads), it leads to breakage. Additionally, it’s a giant waving red flag to Discord.

Shards: Again, technically accepted but useless.

discord.ui: Users cannot send items from the bot UI kit.

discord.app_commands: Users cannot register application commands.

#

From the docs

oblique adder
robust fulcrum
#
import discord
from discord.ext import commands
import asyncio

class Select(discord.ui.Select):
    def __init__(self):
        options=[
            discord.SelectOption(label="Send!",emoji="✍🏻",description="Send the suggestion!"),
            discord.SelectOption(label="Cancel!",emoji="❌",description="Cancel the suggestion!")
            ]
        super().__init__(placeholder="Select an option",max_values=1,min_values=1,options=options)
    async def callback(self, interaction: discord.Interaction):
        if self.values[0] == "Send!":
            await interaction.response.send_message(content="successfully sent!",ephemeral=True)

class SelectView(discord.ui.View):
    def __init__(self, *, timeout = 180):
        super().__init__(timeout=timeout)
        self.add_item(Select())

class suggest(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        
    @commands.command()
    async def dm(self, ctx,user:discord.Member = None ):
        def check(msg):
            return msg.author.id == ctx.author.id and msg.channel.id == ctx.channel.id
        await ctx.send("**Send the message you want to send **",delete_after=5)
        mes = await self.bot.wait_for('message', check=check,timeout=20)
        mes = (mes.content)
        await ctx.send(f"This is your message:**{mes}** -\/ select the option below", view=SelectView(),delete_after=5)
        


async def setup(bot):
	await bot.add_cog(suggest(bot))

I made a command to send a dm
I want that when someone select send option from dropdown it sends dm
So where I have to put bot.send_message()?

west escarp
#

Discord.py-self is a self botting library, and we don't permit help with self-bots here

robust fulcrum
#

Yes :-()

west escarp
#

!mute 485776789277507585

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1654259218:f> (59 minutes and 59 seconds).

robust fulcrum
#

Bruh ;-; talk properly

visual island
#

Hmm, I wonder why some people are like that

robust fulcrum
#

Can I say something pls

#

I have something to show ........

#

See what that guy doing with me

west escarp
#

!ban 485776789277507585 nazi references, discord selfbotting, and for completion's sake, blatant disrespect of staff and harassment of other users

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied ban to @real geode permanently.

maiden fable
#

Thanks Bast

#

Hi there brad

robust fulcrum
velvet compass
robust fulcrum
robust fulcrum
paper sluice
west escarp
#

Unfortunately it's very outdated

maiden fable
#

Please don't copy from stack, especially dpy since most of the answers there are from the async version

west escarp
#

dpy changed itself.. 4 times now..?

maiden fable
west escarp
#

And there's outdated code from all four versions out there, and stackoverflow is honestly terrible about updated questions

maiden fable
#

Pre v1
v1
v2

robust fulcrum
maiden fable
#

Idk I started dpy when it was on idk, 1.5 or smth? (2 years ago)

visual island
#

async -> rewrite -> v2 I guess

west escarp
#

did they call it v1 when it became async?

robust fulcrum
#

I started at 2.0 ;-;

maiden fable
west escarp
#

Because there was a sync version before that

maiden fable
west escarp
#

yes

maiden fable
#

Literal sync methods?

west escarp
#

yep

robust fulcrum
#

Sed

maiden fable
#

Damn, that's.....

visual island
#

How did they handle events..

west escarp
#

Syncly

maiden fable
#

Lmao imagine if 2 people run a command at the same time

robust fulcrum
#

Hmm is dpy maintained these day?

paper sluice
west escarp
robust fulcrum
#

Actually I never used this decorator

maiden fable
#

!d discord.ui.select

unkempt canyonBOT
#

discord.ui.select(*, placeholder=None, custom_id=..., min_values=1, max_values=1, options=..., disabled=False, row=None)```
A decorator that attaches a select menu to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Select`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Select "discord.ui.Select") being used.

In order to get the selected items that the user has chosen within the callback use [`Select.values`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Select.values "discord.ui.Select.values").
robust fulcrum
#

Ig writing something big

maiden fable
#

Good thing the deco also exists

paper sluice
# robust fulcrum In callback?

no the way to use it is

class MYSelectOption(discord.ui.View):
      def __init__(...):
          ...
          super().__init__(...)
      
      @discord.ui.select(placeholder=..., options=[discord.SelectOption(...), ...])
      async def callback(self, interaction: discord.Interaction, select: discord.ui.Select) -> None:
          # now do what u want here
robust fulcrum
paper sluice
visual island
maiden fable
#

Oh u found it

#

what in the

paper sluice
#
794991a
on Aug 22, 2015
Git stats
 6 commits
maiden fable
#

Lmao best source code ever tbh
THE most easiest and non confusing

robust fulcrum
#

Whats this

maiden fable
#

Dpy in 2015

visual island
#

That's neat

robust fulcrum
#

Lol

maiden fable
#

Lol the server class

robust fulcrum
#

Guys is it possible to make our own api?

maiden fable
#

Ofc
Gonna be a fun experience if u know what u r doing

robust fulcrum
paper sluice
#

yes

#

!d discord.SelectOption

unkempt canyonBOT
#

class discord.SelectOption(*, label, value=..., description=None, emoji=None, default=False)```
Represents a select menu’s option.

These can be created by users.

New in version 2.0.
robust fulcrum
paper sluice
#

u put that in the SelectOption

paper sluice
robust fulcrum
#

Oh

#

I think i did something wrong

paper sluice
#

that list of SelectOptions will be all the options in ur select menu

robust fulcrum
#

Is it wrong?

paper sluice
#

yes

robust fulcrum
#

Do i need to make 2?

#

Like 1 for 1 option

paper sluice
#

ur supposed to do label='...', value='...' they are keyword only args

paper sluice
slate swan
#

How do events work in dpy

robust fulcrum
#

Oof means i did wrong

unkempt canyonBOT
#

examples/views/dropdown.py lines 14 to 19

# Set the options that will be presented inside the dropdown
options = [
    discord.SelectOption(label='Red', description='Your favourite colour is red', emoji='🟥'),
    discord.SelectOption(label='Green', description='Your favourite colour is green', emoji='🟩'),
    discord.SelectOption(label='Blue', description='Your favourite colour is blue', emoji='🟦'),
]```
lyric apex
#

This error stops my loop how to fix that

paper sluice
robust fulcrum
#

@paper sluice

@bot.event
async def on_ready():
    bot.add_view(MyView()) # Registers a View for persistent listening

class MyView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None) # timeout of the view must be set to None

    @discord.ui.select(custom_id="select-1", options = [...]) # a custom_id must be set
    async def select_callback(self, select, callback):
        ...

@bot.command()
async def button(ctx):
    await ctx.send(f"View persistence status: {MyView.is_persistent(MyView())}", view=MyView())

You mean this :)

#

I found it on pycord docs

robust fulcrum
lyric apex
paper sluice
robust fulcrum
#

Oh k

lyric apex
paper sluice
#

cats lemon_hyperpleased

lyric apex
#

Cats Are LoveQtpie

#

@robust fulcrum what happenedQtpie

robust fulcrum
#

@paper sluice


    @discord.ui.select(custom_id="select-1", options = ["send!"],emoji="❤️") 
    async def select_callback(self, select, callback):

This fine?

paper sluice
robust fulcrum
#

Ah my mind breaking from thus decorator

robust fulcrum
#

And this decorator out of class

paper sluice
#

and u put the label, emojis etc in those selectoption

#

ur using pycord?

robust fulcrum
#

No

#

I gtg Bai I'll do it lator

slate swan
#

can some on help me

#

some one?

drifting arrow
#

@slate swan what do you need help with?

slate swan
#

`import discord
import random

TOKEN = 'no'

client = discord.Client()

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

@client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')

if message.author == client.user:
return
if message.channel.name == 'general-wont-work':
if user_message.lower() == 'hello'
await message.channel.send(f'Hello {username}!')
return
elif username_message.lower() == 'bye'
await message.channel.send(f'Hello {username}!')
return
elif user_message

client.run(TOKEN)`

drifting arrow
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

slate swan
#

ohh

#
import random

TOKEN = 'no'

client = discord.Client()


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


@client.event
async def on_message(message):
  username = str(message.author).split('#')[0]
  user_message = str(message.content)
   channel = str(message.channel.name)
   print(f'{username}: {user_message} ({channel})')


   if message.author == client.user:
       return
    if message.channel.name == 'general-wont-work':
         if user_message.lower() == 'hello'
             await message.channel.send(f'Hello {username}!')
             return
           elif username_message.lower() == 'bye'
        await message.channel.send(f'Hello {username}!')
             return
     elif user_message



client.run(TOKEN)```
drifting arrow
#

so whats the issue?

slate swan
#

it wont work

#

its showing errors

#

@drifting arrow

drifting arrow
#

your indents are wrong

slate swan
#

how

#

i dont get indents

#

can you fix it for me?

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

drifting arrow
#

No. You need to understand indentation better.

slate swan
slate swan
#

let me try

#

from discord.ext import commands

#

like this u import

#

ok

#

can you fix it for me

drifting arrow
#

@slate swan 😄 no.

slate swan
#

I don't really suggest copying code

#

@slate swan do u have any python knowledge

drifting arrow
#

Anyway. back to why I came here to begin with. Is there a way to tell if a message content is just a file?

slate swan
#

im new its my first month

slate swan
#

idk

slate swan
#
from discord.ext import commands
bot = commands.Bot()
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

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

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

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

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

How do I get guild banners and member banners?
I am doing this rn but it doesn't work:

    @commands.command(name='guildbanner', description='view a guilds banner', usage='guildbanner (guild id)', aliases=['gb', 'serverbanner', 'sb'])
    async def guildbanner(self, ctx):
        if ctx.guild.banner is None:
            e = discord.Embed(
                description=f'{ctx.author.mention}: {ctx.guild.name} doesn\'t have a **banner**',
                color=0xf8a424
            )
            await ctx.send(embed=e)
        else:
            await ctx.send(f'**{ctx.guild.name}\'s banner**\n'
                           f'{ctx.guild.banner.url}')

    @commands.command(name='banner', description='view the banner of a user', usage='banner (user)')
    async def banner(self, ctx, member: discord.Member = None):
        member = ctx.author if member is None else member
        if member.banner is None:
            e = discord.Embed(
                description=f'{ctx.author.mention}: {member.mention} doesn\'t have a **banner**',
                color=0xf8a424
            )
            await ctx.send(embed=e)
        else:
            await ctx.send(f'**{member}\'s banner**\n'
                           f'{member.banner.url}')
scarlet aurora
vital glacier
#

no error

#

it's giving me the Embed, let me see if i can print the error

slate swan
vital glacier
slate swan
#

Ye

vital glacier
#

nah i cant print the error

#

it's not letting me

slate swan
#

u sure it's d 2.0

vital glacier
#

mhm

#

im 100% sure

slate swan
#

Ash will help u

vital glacier
#

LOL

slate swan
vital glacier
#

hi ashley

slate swan
#

hi north

vital glacier
#

can u help me perhaps

vital glacier
slate swan
#

do you have the members intent enabled?

vital glacier
#

yeah

#

because all my other member commands work too

#

it's just the banner ones that don't work

drifting arrow
#

How can I get my bot to open a file sent in chat?

slate swan
vital glacier
slate swan
drifting arrow
#

i've tried that lol

slate swan
drifting arrow
#
 # Listens for any errors and displays them to the user.
    @commands.Cog.listener()
    async def on_message(self, message):
        if not message.author.bot:
            message_channel = message.channel
            if message.attachments:
                await message_channel.send('Theres an attachment!')
                message_attachment = message.attachments
                print(message_attachment)
                for attachment in message_attachment:
                    if 'vdf' in attachment.filename:
                        myvdf = vdf.load(open(attachment.file))
                        print(myvdf)
vital glacier
#
    @commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        ignored = (commands.CommandNotFound, commands.UserInputError)
        if isinstance(error, ignored):
            print(error)

        if isinstance(error, commands.CommandOnCooldown):
            m, s = divmod(error.retry_after, 60)
            h, m = divmod(m, 60)
            if int(h) == 0 and int(m) == 0:
                await ctx.send(
                    f' {ctx.author.mention}, you must wait **{int(s)}** seconds to use the **{ctx.invoked_with}** command!')
            elif int(h) == 0 and int(m) != 0:
                await ctx.send(
                    f' {ctx.author.mention}, you must wait **{int(m)} minutes** and **{int(s)} seconds** to use the **{ctx.invoked_with}** command!')
            else:
                await ctx.send(
                    f' {ctx.author.mention}, you must wait {int(h)} hours, {int(m)} minutes and {int(s)} seconds to use the **{ctx.invoked_with}** command!')
        elif isinstance(error, commands.MissingPermissions):
            missing = [perm.replace('_', ' ').replace('guild', 'server').title() for perm in error.missing_permissions]
            if len(missing) > 2:
                fmt = '{}, {}'.format(", ".join(missing[:-1]), missing[-1].lower())
            else:
                fmt = ' and '.join(missing)
            _message = '{}: **{}** requires the `{}` permissions'.format(ctx.author.mention, ctx.invoked_with,
                                                                         fmt.lower())
            e = discord.Embed(
                description=f'{_message}',
                color=0xf8a424
            )
            await ctx.send(embed=e)
        print(error)
slate swan
#

try print(member.banner)

vital glacier
#

still need to make it better tho

slate swan
#

so we can see

#

What's the error

slate swan
vital glacier
#

i did return error before

#

but that also didnt give me anything

slate swan
#

and the indents are messed up ig

slate swan
#

um banner

#

is None

vital glacier
#

which is true because i dont have a member

#

banner*

#

But now I tried it with someone with a banner, and it gave me the same thing

vital glacier
vital glacier
#

i even changed member = ... to member = member or ctx.author

slate swan
#

wheres the code uhh

vital glacier
#

Oh wait, is it cus i did member: discord.Member = None?

slate swan
#

no

vital glacier
#

huh

slate swan
#

code

vital glacier
#

This you mean?

#

or my current code of what im tryna do now>

#
    @commands.command(name='banner', description='view the banner of a user', usage='banner (user)')
    async def banner(self, ctx, member: discord.Member = None):
        member = member or ctx.author
        print(member.banner.url)
slate swan
#

weird

vital glacier
#

yeah

#

that's what i mean

slate swan
#

it should work since members intent is enabled too

vital glacier
#

Yeah, and the person I mentioned with a banner even gave me the same error

visual island
vital glacier
#

and how do i fetch it?

visual island
vital glacier
#

but how do i even get the banner from that

visual island
vital glacier
#

Ah

#

alright, let me check it out

drifting arrow
#
b'"users"\n{\n\t"76561198425649012"\n\t{\n\t\t"AccountName"\t\t"robertmarius8"\n\t\t"PersonaName"\t\t"bob"\n\t\t"RememberPassword"\t\t"1"\n\t\t"WantsOfflineMode"\t\t"0"\n\t\t"SkipOfflineModeWarning"\t\t"0"\n\t\t"AllowAutoLogin"\t\t"1"\n\t\t"MostRecent"\t\t"1"\n\t\t"Timestamp"\t\t"1654036305"\n\t}\n}\n'

When I open a vdf file that I sent as attachment and print it, this is what I get.. How do I clean it up and make it more readable?

if 'vdf' in attachment.filename:
                        attachment_url = attachment.url
                        file_request = requests.get(attachment_url)
                        data = file_request.content
                        await message.channel.send(data)
                        print(data)
maiden fable
#

What's this

#

!pypi vdf @drifting arrow

unkempt canyonBOT
#

Library for working with Valve's VDF text format

maiden fable
#

Also, use aiohttp not requests

visual island
drifting arrow
#

im trying to use that but it's not working

strange vessel
#
async def on_member_join(member):
  guild = client.get_guild(980542229015830568)
  channel = guild.get_channel(980542229015830568)
  await channel.send('Welcome to the server {member.mention}! Be sure to regulate with rules and verify.') # Welcome the member on the server ````

How come this simple welcome doesnt work with no error and i did enable the intent
maiden fable
#

Ngl, I wish there was a way Python allowed us to make a sync and an async function of the same name in the same namespace, which would do different things based on whether it was awaited or not

#

get_member -> Get from cache
await get_member -> Fetch from API

#

Would be fun ngl

visual island
#

Oh, that's a great idea

dawn shard
maiden fable
#

Ik ik

#

U didn't understand me

visual island
maiden fable
#

Or idk mess with the builtins module?

visual island
#

I'll try something

maiden fable
#

Cool

boreal ravine
dull river
#

@worn lintel

slate swan
visual island
# maiden fable Cool

The problem is that doing await foo() calls foo.__call__(), so we will never know if it's awaited

maiden fable
visual island
#

This is my best approach, to call the sync func, you need to call it twice

pliant gulch
#

You can just catch it and then that’ll let you know it wasn’t awaited

#

!d warnings.catch_warnings

unkempt canyonBOT
#

class warnings.catch_warnings(*, record=False, module=None)```
A context manager that copies and, upon exit, restores the warnings filter and the [`showwarning()`](https://docs.python.org/3/library/warnings.html#warnings.showwarning "warnings.showwarning") function. If the *record* argument is [`False`](https://docs.python.org/3/library/constants.html#False "False") (the default) the context manager returns [`None`](https://docs.python.org/3/library/constants.html#None "None") on entry. If *record* is [`True`](https://docs.python.org/3/library/constants.html#True "True"), a list is returned that is progressively populated with objects as seen by a custom [`showwarning()`](https://docs.python.org/3/library/warnings.html#warnings.showwarning "warnings.showwarning") function (which also suppresses output to `sys.stdout`). Each object in the list has attributes with the same names as the arguments to [`showwarning()`](https://docs.python.org/3/library/warnings.html#warnings.showwarning "warnings.showwarning").

The *module* argument takes a module that will be used instead of the module returned when you import [`warnings`](https://docs.python.org/3/library/warnings.html#module-warnings "warnings: Issue warning messages and control their disposition.") whose filter will be protected. This argument exists primarily for testing the [`warnings`](https://docs.python.org/3/library/warnings.html#module-warnings "warnings: Issue warning messages and control their disposition.") module itself.
slate swan
#

andy smort

tacit token
#

Hi anybody have any idea how can i make this timer? X minutes X seconds ago.

visual island
strange vessel
lyric apex
maiden fable
# maiden fable Yup

Like u gotta implement them manually in the lib. But the issue is, where to catch the warning and how to get the function name

keen mural
#

Can someone link me to the docs where i can get all the info about a member

lyric apex
#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s name with the discriminator.
lyric apex
#

This?

keen mural
#

Thanks

vale wing
#

Lemme dive into asyncio docs

heady sluice
#

some people would put await randomly and be making API calls accidentally

vale wing
#

Yes might be confusing

#

Since we can consider it a kind of overload

#

Overloads are not "native" for python

visual island
vale wing
#

Ima look into asyncio source

edgy jetty
#

!voiceverify

pliant gulch
#

It’s pretty easy to override the warning message class, hook the call getting the source, which is the coroutine. Then continuing from there

slate swan
maiden fable
robust fulcrum
#

How to add reaction in dpy 2.0?

#

Use pil

#

Means you want paste a png to picture?

visual island
pliant gulch
slate swan
#

upload it?

slate swan
unkempt canyonBOT
#

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

Adds a reaction to the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").

You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.

Changed in version 2.0: `emoji` parameter is now positional-only.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
lyric apex
#

@slate swan Could You Help me how to fix that error my loop stops when the message i fetch is deleted

slate swan
lyric apex
slate swan
lyric apex
slate swan
lyric apex
lyric apex
slate swan
maiden fable
vale wing
slate swan
lyric apex
vale wing
maiden fable
#

Invisible chars

vale wing
#

Trying to figure out why tf they use it

#

Sorry for bothering

lyric apex
lyric apex
vale wing
#

What code editor is this anyway

lyric apex
#

Thats the code

vale wing
lyric apex
vale wing
#

Ah

lyric apex
#

Not the errorQtpie

vale wing
#

Man sorry I am annoying

lyric apex
#

NpQtpie Go Through the code i am getting a problem like my loop is working fine if the message is present but sometimes the user deletes it so how to avoid it

maiden fable
lyric apex
vale wing
#

Why not use async wrapper

lyric apex
#

This is what the output when message exists

lyric apex
vale wing
#

You have sqlite? Switch to aiosqlite

lyric apex
maiden fable
#

@visual island so in the class u r accepting two funcs, one which can be called normally and one which can be called asynchronously?

vale wing
#

psycopg2 -> asyncpg

lyric apex
visual island
maiden fable
#

Yea I was also seeing that

#

What the, builtins module doesn't have an Awaitable or Coro class

#

Prolly andy was right, gotta mess with the warnings module

#

But the main issue would be, how to catch the warnings during runtime since there is no function (in discord.py or any other lib) which is invoked whenever a new request is done

jaunty venture
#

how can i set choices in slash commands

#

?

#

@maiden fable

maiden fable
#

I haven't really used slash commands much, sorry

jaunty venture
visual island
maiden fable
visual island
#

BTW, still waiting for Andy's solution kobopeek

maiden fable
#

@pliant gulch

pliant gulch
#

In a meeting

maiden fable
#

Ah okay

pliant gulch
#

Then I got stuff after that, but I’ll ping you when I write it

maiden fable
#

Sorry for disturbing

visual island
maiden fable
slate swan
livid hinge
#

lol ping war

livid hinge
maiden fable
slate swan
#

@maiden fable

maiden fable
#

Yea?

slate swan
#

pWut go play

maiden fable
#

Not in a battle royale anyways

slate swan
maiden fable
#

Idk, gonna see if I get a stable ping then lmao

slate swan
#

sure pWut

dull terrace
#

Everybody having problems verifying their bot like me lately froggy_chill

#

been over a week with no response to support emails, someone else has been waiting two weeks fml

#

another one got two different emails that said it was fixed and one saying it wasn't doge_kek

paper sluice
#

lmao

maiden fable
dull terrace
#

when you get verified in 20 mins and then there's a bug its just 3142painwithcoffee

slate swan
#

Hi ded chat

vocal snow
#

Hi

slate swan
#

bro

vocal snow
#

I'm sorry I couldn't help it

slate swan
#

smh

vocal plover
#

I find that the best technique around bot verification is just not making public bots kek

#
  • No intent issues
  • No dealing with random users
  • No scaling issues
  • Easy af architecture for both the bot and database schema
slate swan
#

Aka custom bots

dull terrace
slate swan
#

wait wdym didn't work? did you get a bot verified email without the bot getting actually verified?

dull terrace
#

yeah, common bug rn

pliant gulch
paper sluice
#
  • no intrest xD
pliant gulch
#
  • how the hell you gonna monetise?
slate swan
dull terrace
paper sluice
#

D:

paper sluice
pliant gulch
#

🗿

vocal plover
maiden fable
dull terrace
#

if you pay yourself for the bot i'd bet you'd get paid a lot, then you can just use what you earn to pay yourself even more

slate swan
#

Make a bot dashboard site and play ads there

dull terrace
#

not really weird

vocal plover
#

Or a bot that is just really uniquely useful

paper sluice
maiden fable
#

Well I still feel like spending on smth like a discord bot is just an.... overkill

vocal plover
#

I know of some mod bots that have advanced unique paid features which some servers just need

maiden fable
dull terrace
vocal plover
#

Does your 200 member community server need those features? Probably not
Does a server with hundreds of thousands of members need it? Quite possibly

sick birch
maiden fable
#

Agreed, probably cz I know how to code I am not able to see the other person's pov

dull terrace
#

Based on my research if you don't have features offered on your patreon and people just pay out of kindness you earn a little over 0.2c per server

#

game bots with pay to win type stuff get 2c all the way to 14c

sick birch
#

Yet P2W "business strategy" never works out in the long run

dull terrace
#

depends how you approach it robin

maiden fable
#

Agreed

sick birch
#

Personally though I find the discord bot market is more of less taken, there are mostly large bots and people don't often go outside their comfort zone to get smaller bots in

#

I never really went on the commercial side of it for that very reason

vocal plover
maiden fable
vocal plover
#

Private single-purpose commission bots are still widely requested

dull terrace
dull terrace
#

have a good page on top.gg and you'll get decent growth

sick birch
#

But when compared to profits of larger bots, it doesn't seem like all that much

vocal plover
#

indeed

vale wing
sick birch
#

But for an independent developer, it can seem like quite a lot and be more than enough, could even consider it a side hustle

dull terrace
#

to make any sort of money you'd need good conversion and 30k+ servers

#

but the promotion can be net positive if you have retention over 3-4 months (buying cpm at $1)

vale wing
#

Well you didn't just make the page and let it be, did you? You did promote your bot somewhere

sick birch
#

Possible but I'd assume quite difficult like as mentioned the public market is largely dominated by other big bots

dull terrace
#

just let the page be

vocal plover
#

I've got something like 13k servers now, the hardest bit about monetisation for me is actually being motivated to implement it. There's a lot of moving parts that go into making something that realistically very few people will use

paper sluice
#

are discord bots good source of income?

sick birch
#

Not enough to live off of

maiden fable
#

Lets just open a company which is gonna make bots for ppl

sick birch
#

As an indie developer, that is

vocal plover
sick birch
#

If you're making a bot as a fun project by yourself, most likely not going to be able to live off of it

vale wing
#

Just get an IT job you will get decent salary

dull terrace
#

bots are the same as anything else, 20% of people earn 80% of the money and 20% of those 20% make a good amount

vocal plover
#

Or if as mentioned earlier you make private commissions and become trusted and well known

paper sluice
sick birch
#

Marketing is probably the hardest part I'd say

vocal plover
#

To make a public bot that makes a lot of money now you realistically need a lot of money to start with to get there

slate swan
#

.

#

Alr back dc lagged

dull terrace
vale wing
vocal plover
#

MEE6 is proof enough you don't need a good bot, just a popular one lmao

vale wing
#

Lmfao

paper sluice
#

so this is basically a mini business

vale wing
vocal plover
#

MEE6 is objectively worse than most of its competitors, but people know MEE6, which gives it a massive advantage

slate swan
#

its like pycord

dull terrace
#

btw you can do basic maths on patreons that hide their income

vocal plover
dull terrace
#

owobot is earning at least $2058 a month - 10% to patreon

dull terrace
#

most bots i've seen tend to earn just under their mid tier though so i imagine around £3

vocal plover
maiden fable
vale wing
#

That's like 7x my actual salary tho

#

In russia salaries for teachers are low 🥲

dull terrace
#

$3.75 x 2058 = $7718 - 10% = $6945 *12 =

maiden fable
#

u, teacher?

dull terrace
#

$83k per year

paper sluice
paper sluice
sick birch
vale wing
dull terrace
#

owo bot is made by multiple people though (i think) so that's probably split

slate swan
maiden fable
sick birch
#

That's one disadvantage when it comes that

vale wing
#

The sus thing is that my accordion costs $5k

slate swan
unkempt canyonBOT
slate swan
paper sluice
vale wing
#

Moderator

slate swan
#

it needed to be donegrump

dull terrace
paper sluice
slate swan
maiden fable
dull terrace
#

the cap for earning is probably more like $500k a year if you did everything perfectly

vale wing
dull terrace
#

well they did all the work up front so i wouldn't say nothing doge_kek

vale wing
#

Put effort or money and then just collect money

dull terrace
#

i imagine maintaining a bot with that many users is hard af too

shrewd apex
vale wing
#

And most of them usually just put money

vale wing
#

You only need to have a good marketing manager

dull terrace
#

with anything artistic you can't say that though, you have to make multiple attempts before you make anything if you even do

shrewd apex
dull terrace
#

the reward is you can kind of relax and get some income for a few years when you finally get something that works

shrewd apex
vale wing
dull terrace
#

also if you think the discord bot market is oversaturated, try to release something on the play store doge_kek

vale wing
#

Fnaf 69 😉

#

Gonna become game of the year if google allows payments in russia which it won't do ofc

vocal plover
shrewd apex
dull terrace
vale wing
#

The start in marketing is aids

#

Is almost impossible without money

dull terrace
#

the saturation is all balanced based on potential earnings

shrewd apex
#

welp lets stop before someone warns us

maiden fable
#

Oh wait play store talk finished 😔
I wasn't able to brag about the project I am working on give my comments

dull terrace
vocal plover
slate swan
#

discord bots will always be bland, you make a feature its already probably been done, you make a unique one it gets stolen by the top bots and becomes a feature all bots have and the cycle continues!

shrewd apex
#

idk product management in discord bot channel?...

vale wing
#

Well in russia we can't pay to outside countries

vocal plover
#

about discord bots

vocal plover
#

knowing an idea doesnt mean you're gonna be able to recreate it to any level people will want to use

shrewd apex
#

the one who innovates will have an advantage

vale wing
#

Btw aias just hit 50 guilds 😀

dull terrace
#

that's ominous

shrewd apex
#

i mean like the poketwo bot full repo is out but there are no such bots on same level as it is

shrewd apex
dull terrace
#

btw here's an earning sheet for some bots

#

min earn is just the minimum based off of patreon lowest pledge

#

when they don't share their full earnings and just number of patrons

paper sluice
dull terrace
#

yeah the earnings is monthly

paper sluice
#

thats alot just for a discord bot

slate swan
buoyant zodiac
#

d!discord.user.banner