#discord-bots

1 messages · Page 138 of 1

fading marlin
#

I'm not gonna give you some code that you can just copy and paste lmao

hushed ridge
#

You said that man

fading marlin
#

where?

hushed ridge
#

Ok thank you I will ask another one

fading marlin
#

alright

quiet tapir
#

There are a lot of videos on youtube that can help you with what you are looking for @hushed ridge

fading marlin
#

!resources

unkempt canyonBOT
#
Resources

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

slate swan
#

!d discord.Member.ban

unkempt canyonBOT
#

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

Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.ban "discord.Guild.ban").
hushed ridge
#

oh

#

!d help

unkempt canyonBOT
#

help()``````py

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

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

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

but you can use it if you learn from it

quiet tapir
hushed ridge
#

@client.event
async def on_message( message ):
if message.author.bot:
return
else:
member = message.author.name
msg_len = len(message.content)
rand_number_1 = randint( 1, 10 )
exp_first = msg_len * rand_number_1
coins_first = exp_first // 10
data_levels_member_first = { 'exp': 0, 'coins': 0, 'level': 0}
filename = f'./Data/Profiles/Profile{message.author.name}{message.guild}.json'
try:
data = load( filename )
except Exception:
dump( filename, data_levels_member_first )
data = load( filename )
exp_member = data['exp']
coins_member = data['coins']
lvl_member = data['level']
exp = exp_first + exp_member
coins = coins_first + coins_member
lvl = exp ** (1/4)
if lvl_member < lvl:
lvl_member += 1
print('You lvl up!')
data_levels_member = { 'exp': exp, 'coins': coins, 'level': lvl_member}
dump( filename, data_levels_member )
await client.process_commands(message)

this code is right? for leveling system bot

#

Please anyone tell me.

fading marlin
fading marlin
hushed ridge
#

Fix it.

fading marlin
#

that's not my problem nor my job

hushed ridge
#

Bro ur aren't a good helper bruh

fading marlin
#

I'm not a helper, I'm a volunteer spending valuable time trying to help people with problems that they might have with their code. Not giving them copy-paste solutions

quiet tapir
# hushed ridge Bro ur aren't a good helper bruh

How do you wanna learn if you're asking us to just give you the answers?
As he already said, we're not here to just give you the code, but to help and direct you to where you can learn about it

fading marlin
#

hey robin

sick birch
#

hello

hushed ridge
sick birch
#

Is the error not clear?

#

The indents are a bit off

hushed ridge
#

;-;?

#

this problem always happens

#

@client.event
async def on_member_join(member):
with open('users.json', 'r') as f:
users = json.load(f)

await update_data(users, member)

with open('users.json', 'w') as f:
    json.dump(users, f)

the problem is here

unkempt canyonBOT
#

Hey @hushed ridge!

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

hushed ridge
#

I can't upload it xd

#

Wiat

#

Wait *

crisp nexus
#

someone send me all basic commands log call log entry etc

hushed ridge
#

@client.event
async def on_message( message ):
if message.author.bot:
return
else:
member = message.author.name
msg_len = len(message.content)
rand_number_1 = randint( 1, 10 )
exp_first = msg_len * rand_number_1
coins_first = exp_first // 10
data_levels_member_first = { 'exp': 0, 'coins': 0, 'level': 0}
filename = f'./Data/Profiles/Profile{message.author.name}{message.guild}.json'
try:
data = load( filename )
except Exception:
dump( filename, data_levels_member_first )
data = load( filename )
exp_member = data['exp']
coins_member = data['coins']
lvl_member = data['level']
exp = exp_first + exp_member
coins = coins_first + coins_member
lvl = exp ** (1/4)
if lvl_member < lvl:
lvl_member += 1
print('You lvl up!')
data_levels_member = { 'exp': exp, 'coins': coins, 'level': lvl_member}
dump( filename, data_levels_member )
await client.process_commands(message)

#

import json
import discord

try:
with open("users.json") as fp:
users = json.load(fp)
except Exception:
users = {}

def save_users():
with open("users.json", "w+") as fp:
json.dump(users, fp, sort_keys=True, indent=4)

def add_points(user: discord.User, points: int):
id = user.id
if id not in users:
users[id] = {}
users[id]["points"] = users[id].get("points", 0) + points
print("{} now has {} points".format(user.name, users[id]["points"]))
save_users()

def get_points(user: discord.User):
id = user.id
if id in users:
return users[id].get("points", 0)
return 0

@client.event
async def on_message(message):
if message.author == client.user:
return
print("{} sent a message".format(message.author.name))
if message.content.lower().startswith("!lvl"):
msg = "You have {} points!".format(get_points(message.author))
await client.process_commands(message.channel, msg)
add_points(message.author, 1)

client.run(token)

wispy garnet
#

quick question, it has been a long time since I have messed around with discord bot dev, but the github repo for the discord.py library doesn't exist anymore, so i'm not really sure what library is recommended to use

slate swan
#

why does this not work UNBAN ALL

async def unbanall(ctx):
    count = 0
    banned_users = await ctx.guild.bans()
    for ban_entry in banned_users:
        user = ban_entry.user
        await ctx.guild.unban(user)
        count += 1
    await ctx.channel.send(f"unbanned {count}")```
fading marlin
fading marlin
#

!d discord.Guild.bans

unkempt canyonBOT
#

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

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

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

Examples

Usage...
slate swan
#

i dont understand how it works tho

#

Like how I put it into my code

fading marlin
#

there're some examples in the docs

wispy garnet
fading marlin
#

apparently so lol, it happened earlier today

#

if you still want to install dpy, you can use the stable pypi version

wispy garnet
#

alright thanks :)

hushed ridge
#

@fading marlin

#

Do you know in Lua?

fading marlin
#

no

hushed ridge
#

;-;

#

Wtf? 330Billion??

#

Who is that crazy would write this? xD

#

NO WAY!

#

Google Is 2000Billion line

#

,_, 2Trillion wtf? xd

#

Facebook is 60Mil lol xd

#

GTA V is 30 Mil wow xd

sick birch
sick birch
slate swan
hushed ridge
#

;-;

lapis meadow
#

Hello fellow users of discord.py I need help!

So I have it where someone inputs the !stage command and then their stage... It sends a message in another where the FTO will react to the message and when reacted they will get a DM with info! As you can in the lines that have **<----- with the Capital words I need this info from the stage command but I am not smart enough to figure it out! Please someone with big brain help me ^^^^

EX: I need to get the person that originally send the !stage 1 command for the THIS PERSON part
for the RIDE ALONG part I need to get the stage that they put ( Stage being the number in !stage 3)

#
async def stage(ctx, *, stage):
    ftochannel = client.get_channel(1043289756794093639)
    logchannel = client.get_channel(1037550844935147622)
    embed=discord.Embed(title=f"{ctx.author.mention} has requested ride along for stage **{stage}**",description=f"If you want to assist this member with their requested stage react below!", color=0x660066)
    log=discord.Embed(title=f"Discord Log // User Requested Ride Along in BCSO Discord",description=f'Ran By: {ctx.author.mention}\nActual Command Finish: {ctx.author.mention} has just requested the following stage: {stage}! ',color=0x660066)
    emoji = "\N{Large Yellow Circle}"      
    msg = await ftochannel.send(embed=embed)
    await msg.add_reaction(emoji)

    await ctx.send("When an FTO member answers me You will get a message from me with more information! Please be patient!")
    await logchannel.send(embed=log)```
#
async def on_raw_reaction_add(payload):
    if str(payload.emoji) == "\N{Large Yellow Circle}":
        member = payload.member
        sendEmbedToUser = discord.Embed(title=f'Hello!', description=f'You have accepted **THIS PERSONS<---** Stage **RIDE ALONG!<---**\nPlease Arrive in [#1038926472259313732](/guild/267624335836053506/channel/1038926472259313732/) within **10 Minutes**!\n\nHere is some helpful documentation for your ride along:\n[LINK SHORTNER 1]\n[LINK SHORTNER 1]\n[LINK SHORTNER 1]\n[LINK SHORTNER 1]
        await member.send(embed=sendEmbedToUser)```
abstract kindle
#

Any way to check if the user is on 2 devices

sick birch
#

No

abstract kindle
#

I have a guy testing bugs and almost all my commands are broken because a user can just use them at the same time on 2 devices and they'll both go through

#

Even though I have cooldowns, I guess the write to the database isn't fast enough

#

Any way to like, delay processed commands until a previous one has finished?

sick birch
#

Broken how?

sick birch
lapis meadow
#

uhmmmm

lapis meadow
abstract kindle
# sick birch Broken how?

Broken as in like I have a command the gives the user some money. It has a 6 hour cooldown. If a user on 2 different devices uses the command at the same time on each device, they get twice the money

sick birch
abstract kindle
#

I suppose

abstract kindle
slate swan
#

nope

sick birch
#

Not sure if multiple of those properties can be true at once

slate swan
#

it also wont cover up if the user has sync settings on

slate swan
lapis meadow
sick birch
unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
slate swan
#

it says removeGiftcard(‘10dollar.txt), how do i make the value of ‘10dollar.txt’ be logged onto a webhook when it is removed

loud junco
#

im 15 💀

#

discord is for 12+ lmao chill bro

slate swan
#
@miner.tree.command(name='account', description='View yours a friends account!')
@app_commands.describe(user = 'Who?')
async def account(interaction: discord.Interaction, user: str=''):
  id = interaction.user
  with open("users.json", "r") as f:
    users = json.load(f)
  try:
    bitcoin = users[f'{id.id}']['bitcoin'] 
    await interaction.response.send_message(bitcoin)
  except:
    msg = await interaction.response.send_message("You dont have an account! Making one now!")
    with open("users.json", "r") as f:
      users = json.load(f)
    await upd(users, id)
    with open("users.json", "w") as f:
     json.dump(users, f, indent=4)
    asyncio.sleep(2)
    await interaction.response.edit(content=f"{id.mention} Made an account!")
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'account' raised an exception: AttributeError: 'InteractionResponse' object has no attribute 'edit'
loud junco
#
@commands.command()
@commands.cooldown(1, 1, commands.BucketType.user)
async def test2(self, ctx):
    try:
       await ctx.send('1')
       async with connection.cursor() as cursor:
            await cursor.fetch("SELECT part_id, part_name FROM parts ORDER BY part_name")
            rows = cur.fetchall()
        await ctx.send('2')
        await ctx.send(rows)
    except Exception as e:
        print(e)
```how do i define connection in this case
slate swan
loud junco
#

it doesnt exist

slate swan
#

ive tried looking at the docs and I still dont have it

loud junco
#

!d discord.InteractionResponse

unkempt canyonBOT
#

class discord.InteractionResponse```
Represents a Discord interaction response.

This type can be accessed through [`Interaction.response`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.response "discord.Interaction.response").

New in version 2.0.
loud junco
slate swan
#

that is what im reading

loud junco
bright wedge
#

db connect

slate swan
haughty quest
#

I'm jumping back into a bot I made a few years ago, looks like there's been some big updates. Can anyone recommend a walkthrough video that'll catch me up on the basics?

slate swan
# loud junco `await interaction.response.edit(content=f"{id.mention} Made an account!")` this...

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/crypto-miner-bot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'account' raised an exception: InteractionResponded: This interaction has already been responded to before
#

await interaction.response.edit_message(content=f"{id.mention} Made an account!")

sick birch
haughty quest
#

Thanks Robin! That's exactly what I need.

sick birch
#

no worries

bright wedge
loud junco
#
@commands.command()
@commands.cooldown(1, 1, commands.BucketType.user)
async def test2(self, ctx):
    try:
       await ctx.send('1')
       async with connection.cursor() as cursor:
            await cursor.fetch("SELECT part_id, part_name FROM parts ORDER BY part_name")
            rows = cur.fetchall()
        await ctx.send('2')
        await ctx.send(rows)
    except Exception as e:
        print(e)
```how do i define connection in this case
bright wedge
bright wedge
slate swan
loud junco
slate swan
#

where it says removeGiftcard(‘10dollar.txt), how do i make the value of ‘10dollar.txt’ be logged onto a webhook when it is removed

bright wedge
#

!d discord.Message.edit

unkempt canyonBOT
#

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

Edits the message.

The content must be able to be transformed into a string via `str(content)`.

Changed in version 1.3: The `suppress` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.

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

i got rate limited on railway.app 💀

maiden fable
#

You got ratelimited on replit v2

drifting arrow
#

Anybody worked with aiomysql before?

hot cobalt
#

Uh has danny been kicked from github or something? 👀

hot cobalt
#

Oop, must be from the dpy server, I think I left that

#

What's the tldr?

paper sluice
#

he basically got shadowbanned

#

stuff is still there though, they are working on recovering it

loud junco
little lava
#

Can i apply tasks.loop inside the normal chat trigger callback?
like update channel name thing

haughty quest
#

`def run_discord_bot():
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix='!', intents=intents)

@bot.command()
async def new_user(ctx, target, real_name=None):
    print("AHHHHHH")
    db = db_connect.DB()
    db.insert_user(target, real_name)`

Is there any obvious reason why my new_user command wouldnt be triggering at all? no errors, no feedback from the print statement

abstract kindle
#

why can't we have custom colors on our buttons

#

that would literally be so damn nice

haughty quest
haughty quest
#

o

vocal snow
#

Are you running the bot instance

#

Anyways there's no reason to have both a client and bot

#

bot is just an extension of client

haughty quest
#

`bot = commands.Bot(command_prefix='!', intents=intents)

@bot.command()`

isn't that these 2 lines?

#

oo maybe thats it then

vocal snow
#

Where are you calling bot.run is my question

#

Because if you aren't running it then your commands won't work

haughty quest
#

o interesting. so my client and bot do the same thing?

vocal snow
#

Bot is Client with the command extension

haughty quest
#

so if im wanting to do commands, i should just use bot?

vocal snow
#

Yes

haughty quest
#

ok awesome. ill make that change, and hopefully you wont hear back from me about this

#

will mean you fixed it, thanks!

split forge
#
  File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/container/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'redeem' raised an exception: AttributeError: 'Interaction' object has no attribute 'add_roles'```
split forge
shrewd apex
#

result is None

slate swan
#

Who muted me bro

shrewd apex
#

in embed where u do result[1] make it result[1] if result else 0

#

yes

split forge
slate swan
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

split forge
#

did you use rasbyte?

#

how

#

rasbyte has same ui

shrewd apex
split forge
#

thanks

shrewd apex
#

yep

slate swan
unkempt canyonBOT
#
Bad argument

Converting to "int" failed for parameter "pep_number".

split forge
split forge
#

verifed bot??????

severe mural
severe mural
upbeat gust
#

It tells you exactly what's missing and where to install it

split forge
upbeat gust
#

???

severe mural
#

but install sigh

severe mural
severe mural
upbeat gust
severe mural
#

but my little first time.

upbeat gust
#

What?

severe mural
#

... first time

#

no?

upbeat gust
#

pip install discord.py not just pip discord.py

upbeat gust
severe mural
#

correct?

upbeat gust
#

Yes

severe mural
#

okay moment try.

upbeat gust
#

You'll still get the same error

severe mural
#

maybe.

#

nothing solution t.t

upbeat gust
paper sluice
#

upgrade your pip

upbeat gust
severe mural
severe mural
upbeat gust
#

????

severe mural
#

missing Wheel?

#

..

upbeat gust
#

Please try reading

severe mural
#

yes Why error?

#

no solution and search google sigh.

upbeat gust
#

you would know if you read it

#

I've even told you it's in the first screenshot

severe mural
#

sigh think is "pip install pyproject-toml"?

severe mural
#

i am no good english

upbeat gust
paper sluice
severe mural
severe mural
upbeat gust
severe mural
#

hmmm ok i see noted.

upbeat gust
#

Wdym ah did you not see that

severe mural
#

yeah no see nothing but is lag server

#

ram server 😛

paper sluice
severe mural
#

thanks @upbeat gust ok

#

and different pip vs pip3

#

or pip (any 1 , 2 and 3) no?

#

thre commands "pip3"

upbeat gust
#

??

#

I can barely make out what you're saying

severe mural
#

explain differents What is PIP3?

#

and different PIP?

paper sluice
severe mural
#

i see only pip right?

#

not linux pip3

upbeat gust
severe mural
#

ok thanks memory..

split forge
#

only owner is not working

slate swan
#
@slvl.command()
@commands.has_permissions(administrator=True)
async def enable(ctx):
    async with bot.db.cursor() as cursor:
        await cursor.execute("SELECT levelsys FROM levelSettings WHERE guild = ?", (ctx.guild.id,))
        levelsys = await cursor.fetchone()
        if levelsys:
            if levelsys[0]:
                return await ctx.send("The leveling system is already enabled! ")
            await cursor.execute("UPDATE levelSettings SET levelsys = ? WHERE guild = ?", (True, ctx.guild.id,))
        else:
            await cursor.execute("INSERT INTO levelSettings VALUES (?, ?, ?, ?, ?), PRIMARY KEY (guild, user)", (True, 0, 0, 0, ctx.guild.id,))
        await ctx.send("Enabled the leveling system")
    await bot.db.commit()
upbeat gust
#

not the insert

slate swan
#

do i do that in the table

#

@upbeat gust

upbeat gust
#

Yes

slate swan
upbeat gust
#

RIMARY

slate swan
#

OH

upbeat gust
#

why is this inside the columns?

#

you should really go through that tutorial

slate swan
#

do i do that outside

#

yes i will

#

nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: IntegrityError: UNIQUE constraint failed: levelSettings.id
same error

rapid knoll
#

how do I find the role of a member and give them a role if they don't have it?

upbeat gust
shrewd apex
#

second unique here failed coz somewhere u tried to insert a row with same key again

#

so check ur insert statements

naive briar
#

Basic SQLite moment ducky_yellow

shrewd apex
# slate swan that doesnt worj

its full of mistakes whats integerp and u didn't even declare data type for primary key at this point u are just adding stuff in a sentence and praying it works

split forge
#

how to make only command on python is_owner is not working

naive briar
#

What

split forge
#

is_owner is not wokring

naive briar
#

What is not working

candid escarp
# split forge is_owner is not wokring

Please elaborate on your problem instead of just saying "not working?" Provide a full traceback or an error report, otherwise we won't be able to help.

split forge
#

yes

#

nopee

#

wait

#
@tree.command(name='gen', description='generate keys')
@commands.is_owner()
async def redeem(interaction: discord.Interaction, amount: int):```
#

I made a generate and redeem command

#

but is not wokring

#
@commands.is_owner()
async def redeem(interaction: discord.Interaction, amount: int):
    key_amt = range(int(amount))
    f = open("keys.txt", "a")
    show_key = ''
    for x in key_amt:
        key = str(uuid.uuid4())
        show_key += "\n" + key
        f.write(key)
        f.write("\n")

    if len(str(show_key)) == 37:
        show_key = show_key.replace('\n', '')
        await interaction.response.send_message(f"**{show_key}**")
        return 0
    if len(str(show_key)) > 37:
        await interaction.response.send_message(f"**{show_key}**")
    else:
        await interaction.response.send_message(":negative_squared_cross_mark:")```
upbeat gust
#

because commands.is_owner is for message commands

#

why are you even using slash for an owner only command

#

everyone will see

split forge
#

ohhhhhhh

#

okayyyyy

agile oak
#

bro i need help

trim citrus
#

hi,
I am trying to make buttons and have this code. I don't understand why it isn't working.

class yesNoMenu(discord.ui.View):
    def __init__(self):
        super().__init__()


    @discord.ui.button(label = "yes", style=discord.ButtonStyle.green)
    async def yes_butn(self, button: discord.ui.Button, interaction: discord.Interaction):
        await interaction.response.send_message("yes")

    @discord.ui.button(label="no", style=discord.ButtonStyle.red)
    async def yes_butn(self, button: discord.ui.Button, interaction: discord.Interaction):
        await interaction.response.send_message("no")

@client.tree.command(name="test")
async def test(interaction: discord.Interaction, person: discord.Member):
    view = yesNoMenu()
    await interaction.response.send_message("Yes or no?", view=view)

For some reason, it's adding only 1 button, but not both.

agile oak
#

i solved the intents glitch

#

but when i run the code in replit it gives another error

#

i need some on to collaborate with me

naive briar
#

Change one of them

naive briar
agile oak
trim citrus
agile oak
#

please help

honest shoal
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.

agile oak
#

bro the thing i need to show you is the error

naive briar
#

Then copy the error and send it

agile oak
#

code

upbeat gust
#

you still havent shown the error

hot cobalt
#

Is there any documentation and/or quickstarts out there for discord.py's slash command features?

#

I don't see anything in the site, could just have overlooked it though

#

oop nevermind, the gist in the pins seems to cover it nicely

slate swan
#

ashley ftw
discord.py maintainers were also working on an official guide idk whats the progress tho

#

how do i display a user’s pfp in an embedded message with a python code

#

!d discord.User.avatar for the pfp

unkempt canyonBOT
#

property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/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/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
slate swan
#

!d discord.Embed.set_image for setting the pfp as image

unkempt canyonBOT
#

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

This function returns the class instance to allow for fluent-style chaining.
slate swan
#

How do i make my bot status like watching (members) in (guilds)

#

or something like that

#

!d discord.Client.change_presence

unkempt canyonBOT
#

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

Changes the client’s presence.

Example

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

so i made an echo command:

@bot.command(name='echo')
async def name(ctx, *, repeat: str):

    if ctx.author.id == 654818715183087626:
        await ctx.send(f"{repeat}")
        await ctx.message.delete()
        return

    else:
        await ctx.message.delete()
        return

but i want it to be able to sent in other channels, how would i do that? (i.e !echo #b 'Hello' (sent in #a))

slate swan
#
async def foo ( ctx, c: discord.TextChannel,*, stuff):
   await c.send(stuff)
verbal monolith
#

hold on

#
@bot.command(name='echo')
async def name(ctx, c: discord.TextChannel, *,  repeat: str):

    if ctx.author.id == 654818715183087626:
        await ctx.send(repeat)
        await ctx.message.delete()
        return

    else:
        await ctx.message.delete()
        return
#

? @slate swan

slate swan
#

ctx.send sends to invocation channel... you need to use c.send

verbal monolith
slate swan
#

yeah

verbal monolith
#

oooh tyy

#

question if i wanted to make it cross-serveral, would i make it discord.TextChannel.id?

#

@slate swan

slate swan
#

no it will still work

verbal monolith
#

how so ?

slate swan
verbal monolith
#

oh

#

so i can just do !echo #server2channel Hi i n server 1?

slate swan
#

yes

verbal monolith
#

but what if theres multiple channels called the same thing, i.e general?

slate swan
#

use the id or mrnyit

verbal monolith
#

would it not be better to just use discord.TextChannel.id?

slate swan
#

*mention

#

you can't

verbal monolith
#

oh

#

how would i do it

#

wait

#

does discord.TextChannel count for both ID and name?

slate swan
#

mention too yes

verbal monolith
#

oooo

#

okay ty

verbal monolith
#

do i need to do @<channelid>?

slate swan
#

make your own converter then

#

1 min

loud junco
verbal monolith
#
await convert(ctx, discord.TextChannel)```?
#

idk i dont rly understand that

slate swan
#

you'll find your solution here

trim fjord
#

beautiful is better than ugly

#

explicit is better than implicit

loud junco
slate swan
#

rust is better than cpp

trim fjord
#

java is better than rust

loud junco
#

php is better than java

slate swan
#

java isnt even low level Kannakillyourself

loud junco
#

its like

#

lower than mariana trench

trim fjord
#

java is better than evferything

#

java is better than rust because it have a huge developer ecosystem and community, along with more frameworks to choose from. Rust have been declining popularity right now so its not the best choice.

slate swan
#

sounds just like py vs js case

#

and something being used in mass doesn't make it better

#

anyways, offtopic

vocal snow
primal token
#

Zeffo took that personally

slate swan
#

😔 rust is an emotion and im rusted

primal token
#

Get some WD-40 and you'll be fine

slate swan
#

the pyo3 keeps declining it

primal token
loud junco
#

every channel im in is just dead

#

🥹

paper sluice
#

rip

loud junco
paper sluice
#

nope

loud junco
paper sluice
#

have patience

obtuse otter
#

Um, hey.
So i have a command which loops through every member in a guild, and if they don't have role xyz, it would assign them those roles.
So my question is, how would i get those peoples' names who Doesn't have the role?

I tried

return member.name``` but it just sends someone who already has it.
.
```py

x = ctx.guild.get_role(...)
y = ctx.guild.get_role(...)
z = ctx.guild.get_role(...)
  
for member in ctx.guild.members:
   if [x, y, z] not in member.roles:
      return "uhh"```
I'm using discord.py 2.0
shrewd apex
dull knot
#

U guys got any good resources for learning how to implement databases to bots?

I just wanna check one out. And if I feel like I still lack understanding, would need to go back to some basic stuff lol

mighty yarrow
#

@client.command(pass_context=True)
async def cemo(ctx):
with open("my_image.png", "r") as file:
file = file.read()
await create_custom_emoji(name="my_image",image=file)

mighty yarrow
naive briar
#

!e

member_roles = ["role1", "role2", "role3"]
target_roles = ["role1", "role2"]

print(target_roles in member_roles)
unkempt canyonBOT
#

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

False
naive briar
# mighty yarrow

Is it in the same directory as the python file that code is in?

mighty yarrow
#

oh yea i forgot about that

naive briar
#

🤨

shell wing
#

Code

    async def on_submit(self, interaction: discord.Interaction):
        view = appresponse()
        await interaction.response.send_message(
            f'Your application was submitted successfully, {interaction.user.mention}!', ephemeral=True)
        embedVar = discord.Embed(title=f"{interaction.user}'s Application",
                                 description=f"User", color=0x351156)
       

        await channel.send(embed=embedVar, view=view)
        await view.wait()
        if view.value is None:
            return
        else:
            await embedVar.reply(f"{view.value} is accepted.")```
error
```py
Traceback (most recent call last):
  File "D:\pythonProject\venv\lib\site-packages\discord\ui\modal.py", line 186, in _scheduled_task
    await self.on_submit(interaction)
  File "D:\pythonProject\main.py", line 91, in on_submit
    await embedVar.reply(f"{view.value} ")
AttributeError: 'Embed' object has no attribute 'reply'

maiden fable
#

you need to do interaction.original_message() or smth and then reply to that or just interaction.followup.reply or smth

shell wing
#

alr

shell wing
maiden fable
#

You can try that

slate swan
#

how do i make a command that creates a role

shell wing
# maiden fable You can try that
Task exception was never retrieved
future: <Task finished name='discord-ui-modal-dispatch-569e8ea75a4b3dc48c4b6f199cd7b0d8' coro=<Modal._scheduled_task() done, defined at D:\pythonProject\venv\lib\site-packages\discord\ui\modal.py:177> exception=InteractionResponded('This interaction has already been responded to before')>
Traceback (most recent call last):
  File "D:\pythonProject\venv\lib\site-packages\discord\ui\modal.py", line 186, in _scheduled_task
    await self.on_submit(interaction)
  File "D:\pythonProject\main.py", line 91, in on_submit
    await interaction.followup.reply(f"{view.value} is accepted.")
AttributeError: 'Webhook' object has no attribute 'reply'

During handling of the above exception, another exception occurred:
naive briar
#

There's no reply method in Webhook object

maiden fable
#

Thought so
You need to fetch the original message and then reply to that or use the undocumented methods to prevent an API call and reply to message

slate swan
maiden fable
unkempt canyonBOT
#

await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., display_icon=..., mentionable=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") for the guild.

All fields are optional.

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

Changed in version 1.6: Can now pass `int` to `colour` keyword-only parameter.

New in version 2.0: The `display_icon` keyword-only parameter was added...
slate swan
#

TYSM

naive briar
#

It looks like he's sending the message with a channel object

maiden fable
#

Huh?

naive briar
maiden fable
#

ah that

mighty yarrow
maiden fable
#

then he can just assign it to a variable and then use reply

slate swan
mental hollow
#

how can I make my bot.user.display_avatar.url into a "bytes-like-object" so i can use it as my avatar in a webhook?

naive briar
#

Read it and put in it io.BytesIO

#

!d discord.Asset.read

unkempt canyonBOT
#

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

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

Or maybe you don't have to put it in BytesIO if I misunderstood something

mental hollow
#
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/jishaku/features/python.py", line 145, in jsk_python
    async for send, result in AsyncSender(executor):
  File "/home/container/.local/lib/python3.9/site-packages/jishaku/functools.py", line 109, in _internal
    value = await base.asend(self.send_value)
  File "/home/container/.local/lib/python3.9/site-packages/jishaku/repl/compilation.py", line 140, in traverse
    async for send, result in AsyncSender(func(*self.args)):
  File "/home/container/.local/lib/python3.9/site-packages/jishaku/functools.py", line 109, in _internal
    value = await base.asend(self.send_value)
  File "<repl>", line 4, in _repl_coroutine
    bytes = _bot.user.display_avatar.url.read()
AttributeError: 'str' object has no attribute 'read'

naive briar
#

No, just user.display_avatar.read not user.display_avatar.url.read

mental hollow
#

I see

#
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/jishaku/features/python.py", line 145, in jsk_python
    async for send, result in AsyncSender(executor):
  File "/home/container/.local/lib/python3.9/site-packages/jishaku/functools.py", line 109, in _internal
    value = await base.asend(self.send_value)
  File "/home/container/.local/lib/python3.9/site-packages/jishaku/repl/compilation.py", line 140, in traverse
    async for send, result in AsyncSender(func(*self.args)):
  File "/home/container/.local/lib/python3.9/site-packages/jishaku/functools.py", line 109, in _internal
    value = await base.asend(self.send_value)
  File "<repl>", line 6, in _repl_coroutine
    web = await _ctx.channel.create_webhook(name = "Aziel", avatar = bot_av, reason = "This was a test!")
  File "/home/container/.local/lib/python3.9/site-packages/discord/channel.py", line 516, in create_webhook
    avatar = utils._bytes_to_base64_data(avatar)  # type: ignore
  File "/home/container/.local/lib/python3.9/site-packages/discord/utils.py", line 591, in _bytes_to_base64_data
    mime = _get_mime_type_for_image(data)
  File "/home/container/.local/lib/python3.9/site-packages/discord/utils.py", line 577, in _get_mime_type_for_image
    if data.startswith(b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A"):
AttributeError: '_io.BytesIO' object has no attribute 'startswith'

#

My code:

import io

bytes = await bot.user.display_avatar.read()
bot_av = io.BytesIO(bytes)
web = await ctx.channel.create_webhook(name = "Aziel", avatar = bot_av, reason = "This was a test!")
await web.send(f"Hey! This was {ctx.author} testing a webhook!")
naive briar
#

Yeah, just pass the bytes in. No need to put it in io.BytesIO

mental hollow
#

ah

#

works, tysm :)

#

how can I validate a discord webhook url?

obtuse otter
#

If you mean the links, it's as follows.

[Click to ...](https://....)```
naive briar
slate swan
#

Hello guys, could somebody help me make a discord bot? Im doing it with python coding language and im making it on replit. But the problem is whenever i run the code the bot doesnt start up

obtuse otter
#

Server rules is the title
Follow discords... Is probably the field name
The links are value

And the are just values with lots of \n

slate swan
naive briar
#

Rate limited

slate swan
#

what does that mean

obtuse otter
obtuse otter
#

... = commands.Bot()
This is called bot deocrators constructors

naive briar
obtuse otter
#

Uh

#

Then?

slate swan
#

so what should i do to fix that

obtuse otter
#

I might have mixed up deocrators and constructors

naive briar
slate swan
obtuse otter
slate swan
#

like this?

obtuse otter
#

No, define them on the 2nd last line

slate swan
#

which ones should i use?

obtuse otter
#

intents = Intents.default
Change it to
intents = discord.Intents.default()

naive briar
obtuse otter
#

Cool

slate swan
#

I removed the 2nd one, and after that the code under client.event got underlined in red

slate swan
obtuse otter
#

And what's the error?

slate swan
#

any way for me to change the ip of the server

obtuse otter
#

On the right side of the console

#

There should be another option

#

Type kill 1 in there

slate swan
#

ah

#

i did it, it was in shell

obtuse otter
#

Ok yeah, now run it

slate swan
#

okay

#

Okay well i got a shorter error this time

obtuse otter
#

🤷‍♀️

slate swan
#
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on all addresses.
   WARNING: This is a development server. Do not use it in a production deployment.
 * Running on <censored ip> (Press CTRL+C to quit)
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 300, in static_login
    data = await self.request(Route('GET', '/users/@me'))
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 254, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "main.py", line 49, in <module>
    client.run("<token here>")
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run
    return future.result()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 702, in runner
    await self.start(*args, **kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 665, in start
    await self.login(*args, bot=bot)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 511, in login
    await self.http.static_login(token.strip(), bot=bot)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 304, in static_login
    raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
 172.31.128.1 - - [19/Nov/2022 17:08:06] "GET / HTTP/1.1" 200 -```
naive briar
#

Your token is invalid

#

Read the error

maiden fable
#

Nice

#

Also using replit very nice

slate swan
#

ok well i put the token in, and the bot starts but it doesnt print "Bot Online" which its supposed to do

maiden fable
#

prolly the print is at the wrong place

#

place it inside on_ready or smth

slate swan
#

i did

#

ok nvm it works now, the bot is online on my discord server

maiden fable
#

Nice, uh

#

That's an embed

slate swan
#

also 1 more thing, how would i make the bot have an embed come with a link?

maiden fable
#

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

x == y Checks if two embeds are equal.

New in version 2.0...
naive briar
maiden fable
slate swan
#

for example, when i send the link theres a embed but my bot doesnt embed when i send link

maiden fable
obtuse otter
maiden fable
naive briar
#

Interesting, didn't know that before

honest shoal
faint mural
#

What the heck? KannaconfusedOwO
Got invoked with: <prefix> pat @ user

    async def pat(
            self,
            ctx: MessageContext,
            user: Union[discord.Member, discord.User],
            *,
            _: Optional[str] = None
    ) -> None:
naive briar
#

What's weird about it

faint mural
#

Did you even read the error?

honest shoal
faint mural
#

Yes, and that has nothing to do with it.
I could also use Member | User and it also screams at me

honest shoal
#

you don't need to use both

faint mural
#

That isn't why it errors

honest shoal
#

isn't that a bad arg

obtuse otter
shrewd apex
#

.User and .Member is diff

faint mural
#

I am not accessing any values which aren't present in both.

shrewd apex
#

also .User is when a person a dming the bot or in dms

#

so no reason u need .User

waxen granite
#

how do you load cogs now in version 2.0?

sick birch
#

Same as before but with await

waxen granite
#

it now retuns None

#

and gives the Nonetype error

#

i havent changed anything other than adding the await thing

tulip tide
# waxen granite how do you load cogs now in version 2.0?

does this example help you?

# Load cogs
initial_extension = []

for filename in os.listdir("./cogs"):
    if filename.endswith(".py"):
        initial_extension.append("cogs." + filename[:-3])

if __name__ == '__main__':
    for extension in initial_extension:
        client.load_extension(extension)```
abstract kindle
#

where are the examples of the buttons

naive briar
abstract kindle
#

thanks

slate swan
#

everytime i close and run the bot the ranks goes to 0 again

#

i use db how do i save it

potent spear
hollow gazelle
#

root@localhost:~# python3 run.py
Traceback (most recent call last):
File "/root/project/script/main.py", line 3, in <module>
from imports import *
File "/root/project/script/imports.py", line 19, in <module>
from discord_slash import SlashCommand, SlashContext
ModuleNotFoundError: No module named 'discord_slash'

potent spear
#

I feel like you've just downloaded some project of a YT video & you're now trying to run it

hollow gazelle
sick birch
potent spear
sick birch
#

It was yesterday

potent spear
#

yup, rip that maintainability

sick birch
#

This is why I don't like the the discord bot "market"

potent spear
#

No idea where people even buy bots etc, I guess that's a good thing

sick birch
#

@hollow gazelle unfortunately I think you've wasted your money here - discord-py-slash-command isn't very good and is no longer on PyPi

hollow gazelle
#

but it workedonce i did it

potent spear
#

it won't for long

sick birch
#

Yeah the library is discontinued i believe

#

discord.py supports slash commands, so we don't need 3rd party libraries like these anymore

slate swan
sick birch
#

What's the problem?

nimble timber
#

Guys, this is my first time writing a bot. I have this problem, I seem to have started the bot, it's logged into the network on the discord server, but for some reason when I run the code it doesn't work.

slate swan
#

What's error

nimble timber
slate swan
nimble timber
slate swan
tulip tide
#

take a look at the console, it may tell you where the error is

nimble timber
slate swan
slate swan
slate swan
slate swan
unkempt canyonBOT
#

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

nimble timber
#

I don't know, a friend did something in the terminal and the problem solved itself.

slate swan
#

!rule 2

unkempt canyonBOT
slate swan
#

Self bots are against tos @slate swan

cloud dawn
#

:

mental hollow
#

oh yeah

#

whoops… tysm

cloud dawn
#

np ducky_dave

dry kelp
#

This happens when im trying to run the bot API web.

#

I suppose some model issues.. OAuth2 tokens are not being saved to db

#
class User(DiscordEntity):
    """Base User model, meant to be reference by extensions"""

    async def fetch(self, bot: InteractionBot) -> DUser | None:
        """Returns the associated user id for the given user Model."""

        return bot.get_user(self.id)


class Welcomer(Guild, Model):
    guild = OneToOneField("Bot.Guild")
    channel_id = BigIntField(null=False)
    enabled = BooleanField(default=False)
    title = TextField(null=True)
    description = TextField(null=True)
    icon = TextField(null=True)
    image = TextField(null=True)
    color = TextField(null=True)
    footer_text = TextField(null=True)
    footer_icon = TextField(null=True)


class OAuth2User(Model):
    """Oauth2 User."""

    id: str
    token: str
    expires_in: int
hushed galleon
dry kelp
#
            oauth_response = await OAuth2User.get(id=member.id)
            print(oauth_response.token)
            add_to_guild(oauth_response.token, member.guild.id, member.id)

I also tried printing the oauth token to see if there's something

#

anyone knows anything about OAuth2 tokens?

sick birch
dry kelp
#

People don't really reply there... Do you have some knowledge for this?

nimble timber
#

import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.presences = True
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.command()
async def ping(ctx):
await ctx.send('pong')

#

Question why the bot answers four times "pong"

dry kelp
#

maybe you are running it 4 times

nimble timber
#

I started to change the answer and restart the bot and now it answers all the answers it had before.

slate swan
#

can someone give me an example of a permissions overwrite ?

slate swan
#

!d discord.PermissionOverwrite the docs should have it

slate swan
faint mural
#

Is it possible to create an separate cog_check without monkey patching discord.py?

hushed galleon
faint mural
#

lgtm

slate swan
loud junco
#

its been 8 hours and nobody is giving my question a sh!t :D

mental hollow
#

how do I store the my bot object in the setup method of an extension in a variable named "Aziel"?

glad cradle
loud junco
mental hollow
cunning lion
#

How do I properly use an array by having my message send only once

slate swan
#

Hello! How do I scrape the contents of a discord embed in a channel?

mental hollow
#

nope

#

extensions

#

random .py file which I want access to my bot object in (ping when reply pls)

faint mural
#

define it in your constructor

primal token
#

!xy

unkempt canyonBOT
#

xy-problem

The XY problem can be summarised as asking about your attempted solution, rather than your actual problem.

Often programmers will get distracted with a potential solution they've come up with, and will try asking for help getting it to work. However, it's possible this solution either wouldn't work as they expect, or there's a much better solution instead.

For more information and examples, see http://xyproblem.info/

jaunty parrot
#

Is it possible to add buttons to existing messages?

upbeat gust
#

message.edit has a view kwarg

jaunty parrot
mental hollow
slate swan
#

how do i display a user’s pfp in an embedded message with a python code

haughty quest
#

whats the best way to reference someones display name?

upbeat gust
#

!d discord.Member.display_name

unkempt canyonBOT
#

property display_name```
Returns the user’s display name.

For regular users this is just their username, but if they have a guild specific nickname then that is returned instead.
upbeat gust
unkempt canyonBOT
#

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

This function returns the class instance to allow for fluent-style chaining.
upbeat gust
#

!d discord.Member.avatar

unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
upbeat gust
#

!d discord.Asset.url

unkempt canyonBOT
haughty quest
slate swan
upbeat gust
#

no you write the url

#
  • means every param after it is kwarg only
hollow bridge
#

Does anyone know how to use BaseActivity in discord.py 2.0

full lily
#

I think that's a parent class to some of the built in activity types that you can choose from. Not sure you're supposed to be using that directly

maiden fable
hollow bridge
#

its alright ive got it to work now

maiden fable
#

Cool

haughty quest
full lily
#

member["display_name"]?

haughty quest
#

im not sure. id like to see "Danco#1903" in my database, but right now im seeing <property object at [memory location]>

upbeat gust
full lily
#

oh

haughty quest
#

yeah

upbeat gust
#

It's an attr of discord.Member

#

You need an instance of discord.Member

full lily
#

you need to have an actual instance of that object

#

how you actually get an instance depends on what you're trying to do

#

if it's a command it should be availbe via context

haughty quest
#

this is what i have right now, line 18

full lily
#

if an event, it should be a param of the event object

haughty quest
full lily
#

what member do you want to insert

upbeat gust
#

Why are you storing their name anyway?

full lily
#

that's the question

haughty quest
#

the target of the command

full lily
#

is this a command func?

upbeat gust
full lily
#

You'd wanna store their id probably, depending on what this is for

haughty quest
#

yeah, im storing their name for tracking a currency, will make easier to read displays

full lily
#

use id!!

upbeat gust
#

Use id, get their name when you actually need to display it

#

There's no reason to store this

haughty quest
#

so when i store the currency that they have, thatll be connected to their disc id. and then when i use a command to show how much currency people have i can pull the display name at that point?

upbeat gust
#

Yes

#

you'd use guild.get_member with their id

haughty quest
#

ok awesome, that makes it way easier

#

thanks for the help

mighty yarrow
slate swan
bright wedge
#

But it's better to fix then 🙄

mighty yarrow
#

not that bvruh

upbeat gust
mighty yarrow
bright wedge
#

Huh

upbeat gust
#

wtf ur question

haughty quest
#

i guess they like having broken code ducky_wizard

bright wedge
#

Just downloaded a random code from GitHub

bright wedge
haughty quest
bright wedge
#

Everything you wanna store from discord (in database or whatever),use the id

haughty quest
#

it made my database way simpler

#

only need 2 tables now

bright wedge
#

That's why ids existing 😆

haughty quest
#

you know, now that i think of it that totally makes sense lol

#

i have a habit of overcomplicating things so this all tracks

trim shadow
#

hello, why my bot in discord can not invite to server?

#

like this

#

not button

torn sail
# trim shadow like this

go to the dev portal. open ur app and go to the oath2 section. then go to general and select the stuff for the default invite

slate swan
#

can i have 2 database on the same on_ready?

vocal snow
slate swan
#

did that and look

hard trail
#

Why do I keep getting this error?

upbeat otter
#

run kill 1 in the shell and it'll reset your IP

hollow agate
naive briar
#

It's called basic Googling

mental hollow
#

I’ve already have a thorough look through that

#

doesn’t tell me how to get my bot object

naive briar
#

Really

#

That is the bot object

mental hollow
#
async def setup(Aziel = bot):
    pass
#

so I can do something like that?

ocean dragon
#

I forgot, what was the method to run synchronous code asynchronously with discord bots / asyncio?

naive briar
#

Why would you set a default value for it

mental hollow
naive briar
#

The load_extension will do all the work

molten aspen
#

can someone tell me why is this happen, i just trying to make discord bot with discordpy, but this happen when i run it...

naive briar
#

Replit got rate limited

molten aspen
#

what should i do

sly fractal
#

“kill 1” in shell

#

It will reset ur ip and refresh

mental hollow
#

like so?

molten aspen
glad cradle
mental hollow
#

I’m not using any classes?

#
import discord

#my custom func 
async def log():
   …

@glad cradle this is somewhat what my file looks like and in my custom func, I want my bot object

slate swan
#

how do i display a users pfp in an embedded message

mental hollow
#

pick which one applies to you

slate swan
mental hollow
#

member objects have a .avatar attribute

glad cradle
tough lance
unkempt canyonBOT
#

property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/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/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
glad cradle
#

You need to subclass commands.Cog only for cogs but yours is an extension, not a cog

slate swan
mental hollow
#

like this?

tough lance
glad cradle
mental hollow
#

I’ll be calling my function since I’m gonna import it

#

from logger (my file name) import log

#

then await log()

#

should do the trick

glad cradle
#

if you'll import it then you don't need to call the class in the setup

#

in your logger you have a bot object right?

mental hollow
#

no

#

I’m trying to get one though

mental hollow
#

my issue is idk how to get my bot object

#

inside this file

glad cradle
#

I do not understand why you need a Bot object in your logger file, in the logger file you usually set and create a custom logger, you don't send log messages or other things

mental hollow
#

#

you’re getting confused with my function name

#

I’m not actually making a logger

#

I was giving you an example

#

for the sake of confusion

glad cradle
#

ah

mighty yarrow
#

need help ith blacklist command

glad cradle
#

otherwise the class will have no Bot object

mental hollow
#

logger.py

import discord

class CustomFunctions:
    def __init__(self, bot: commands.AutoShardedBot)
        self.bot = bot

async def log(ctx):
       await ctx.send(self.bot.user.display_avatar.url)

async def setup(bot):
    await bot.load_extension('logger')
#

like that?

glad cradle
#

CustomFunctions(...) is creating a CustomFunctions object, you can use and access the Bot object only after the initialization of the class (so when you're creating a class object and passing a bot object), if you find a way to import the object out of the file then you can use the class with the Bot object

glad cradle
mental hollow
#

"if you find a way to import the object out of the file then you can use the class with the Bot object"

#

what?

mental hollow
#

utils/logger.py

import discord
from discord import Webhook

class CustomChecks:
    def __init__(self, bot: commands.AutoShardedBot):
        super().__init__()
        
    async def log():
        aziel_avatar = bot.user.display_avatar.url 
        e = discord.Embed(colour = 0x2f3136)
        e.title = "Testing my custom function!"
        e.set_image(url = aziel_avatar)
       
async def setup(bot):
    CustomChecks(bot)

main.py

await bot.load_extension('utils.logger')

cogs/info.py

import discord 
from utils.logger import log

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

    @commands.command()
    async def ping(self, ctx):
        await log()

async def setup(bot):
    await bot.add_cog(Info(bot))
#

@glad cradle like this?

ocean dragon
#

how to run blocking code for discord bot? I forgot

rugged shadow
ocean dragon
#

I remember it blocking other commands, is this no longer the case?

rugged shadow
#

it is most definitely still the case

#

blocking code in an async context blocks the event loop

ocean dragon
#

I remember there was a way to run blocking code

rugged shadow
#

are you talking about asyncio.run_in_executor?

ocean dragon
#

perhaps

#

or ``bot.loop.run_in_executor`??

rugged shadow
#

yep, maybe loops have a run_in_executor

#

dunno, don't know much about asyncio

naive briar
#

Sad

#

Yeah, loops have run_in_executor method

ocean dragon
#

it throws RuntimeError: main thread is not in main loop 🤔

ocean dragon
#

oh shit I fixed it

shrewd apex
#

👍

ocean dragon
#

my blocking code was plotting with matplotlib, I added matplotlib.use("Agg") and now it works :)

slate swan
#

wow new badge

#

do i need to make my bot active or something for that?

glad cradle
# mental hollow <@710570210159099984> like this?

bro you can do

utils/logger.py

...

class CustomChecks:
    def __init__(self, bot):
        self.bot = bot

    async def log(self):
        # access the bot with self.bot
        ...

cogs/info.py

from utils.logger import CustomChecks
...
@commands.command()
async def ping(self, ctx):
    logger_class = CustomChecks(self.bot)
    await logger_class.log()
    ...
...

you don't need to load as extension "utils.logger", you can just import it where you need it

... are elipsis that you can substitute with your previous code

#

I thought you didn't have access to the Bot object where you had to use the class

mental hollow
lucid latch
#

how can i execute command after music ended?

#
voice.play(discord.FFmpegPCMAudio(executable = "C:/ffmpeg/bin/ffmpeg.exe", source = URL, ** FFMPEG_OPTIONS), after= print("Test"))```
vocal snow
#

!d discord.VoiceClient.play

unkempt canyonBOT
#

play(source, *, after=None)```
Plays an [`AudioSource`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AudioSource "discord.AudioSource").

The finalizer, `after` is called after the source has been exhausted or an error occurred.

If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. If no after callback is passed, any caught exception will be logged using the library logger.

Changed in version 2.0: Instead of writing to `sys.stderr`, the library’s logger is used.
vocal snow
#

The finalizer, after is called after the source has been exhausted or an error occurred.

lucid latch
#

ah.. but it called right after play executed

slate swan
#

!passte

vocal snow
#

yes because you didn't pass a callable

slate swan
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

vocal snow
#

you passed None

vocal snow
#

.play(..., after=lambda e: print("whatever"))
naive briar
#

Does it work with functools.partial?

vocal snow
#

yes

lucid latch
#

Sry but what is lambda?

lucid latch
#

Ah

#

Ok thx very much!!

slate swan
#

so i use database for my bot for level system but everytime i rerun the bot the levels goes to 0

#

how can i make it stay like it was

slate swan
vocal snow
slate swan
#

cant here

#

now it is saving it but sending twice

vocal snow
#

Because you're returning on the line above

slate swan
slate swan
vocal snow
slate swan
#

no error btw

naive briar
#

What is sleep a bot

slate swan
#

you make the activity idle

naive briar
#

!d discord.Client - set the status kwarg

unkempt canyonBOT
#

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

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

New in version 2.0.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
slate swan
slate swan
naive briar
unkempt canyonBOT
naive briar
slate swan
lucid latch
#
            voice.play(discord.FFmpegPCMAudio(executable = "C:/ffmpeg/bin/ffmpeg.exe", source = URL, ** FFMPEG_OPTIONS), after=lambda e: music(ctx))```
#

RuntimeWarning: coroutine 'music' was never awaited

#

???

slate swan
#

await it

naive briar
lucid latch
#

SyntaxError: 'await' outside async function

vocal snow
lucid latch
#

wait music(ctx))

#

after=lambda e: asyncio.create_task(music))

#

like this?

glad cradle
slate swan
#

hi guys , how can i set an overwrite for 'everyone' as 'connect' = false

mental hollow
summer flume
#

what do u mean

#

How to import the slash commands? I used the from discord import app_commands and I got this error: ImportError: cannot import name 'app_commands' from 'discord'

summer flume
#

discord library, no?

#

I found someone's tutorial on yt how to do it and it doesnt work for me

#

or how to import the slash commands

slate swan
#

what can i do instead of
int(datetime.datetime.now().timestamp())

bc it says
Command raised an exception: AttributeError: type object 'datetime.datetime' has no attribute 'datetime'

naive briar
slate swan
#

import datetime
from datetime import datetime, timedelta

slate swan
#

do i remove one datetime

naive briar
#

Remove the first one

slate swan
#

okay ty!

drifting arrow
#
@tasks.loop(seconds=30)
async def twitter_stream(self):
        print("Loop started")
        bearer_token = self.config['twitter_token']
        auth = {
            "Authorization": f"Bearer {bearer_token}",
            "User-Agent": "v2FilteredStreamPython"
        }
        url = 'https://api.twitter.com/2/tweets/search/stream'
        session_timeout =  aiohttp.ClientTimeout(total=5)
        async with aiohttp.ClientSession(raise_for_status=True, headers=auth, timeout=session_timeout) as session:
            async with session.get(url) as r:
                async for line in r.content:
                    c = line.decode("utf-8")
                    c = c[:-2]
                    if c:
                        #Do a thing here coz we can.
        print("Loop ended")
``` Why does doing this cause the entire thing to loop back to the start of the function instead of first concluding?
naive briar
#

I don't understand what you're saying

drifting arrow
# naive briar I don't understand what you're saying

So when I run the code.
the first print statement runs. then it hits the clientsession part, where it keeps the connection open.
then once the timer hits (in this case 5 seconds), it returns back to the first print statement instead of going to the next part which is the last print statement

#

session_timeout = aiohttp.ClientTimeout(total=5) is basically saying how long the entire session remains open for.

unkempt canyonBOT
#

discord/ext/tasks/__init__.py lines 155 to 160

self._valid_exception = (
    OSError,
    discord.GatewayNotFound,
    discord.ConnectionClosed,
    aiohttp.ClientError,
    asyncio.TimeoutError,```
vocal snow
#

it catches those exceptions for reconnection

#

I'm not sure if aiohttp raises a TimeoutError but if it does, that might answer your question

drifting arrow
naive briar
#

!e

int("owo")
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | ValueError: invalid literal for int() with base 10: 'owo'
slate swan
#

do i remove the int or?

runic quartz
#

How can i get those members' name?

potent spear
naive briar
#

Get it from audit logs

slate swan
#
@bot.command()
@commands.has_permissions(manage_messages=True)
async def warns(ctx, member: nextcord.Member):
    async with bot.db.cursor() as cursor:
        await cursor.execute("SELECT reason, time FROM warns WHERE user = ? AND guild = ?", (member.id, ctx.guild.id,))
        data = await cursor.fetchone()
        if data:
            em = nextcord.Embed(title=f"{member.name}#{member.discriminator}'s Warnings", color=0x99a2d1)
            warnnum = 0
            for table in data:
                    warnnum += 1
                    em.add_field(name=f"Warning {warnnum}", value=f"Reason: {table[0]} | Date: <t:{int(table[1])}:F>")
            await ctx.send(embed=em)
        else:
            em2 = nextcord.Embed(title="Warning Error", description="No warnings found!", color=nextcord.Color.red())
            await ctx.send(embed=em2)
    await bot.db.commit()```

```nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: invalid literal for int() with base 10: 'o'
#

hello guys i need help with a prefix bot in discord. its supposed to say of i type ?id to reply, but i couldn't find anything that could help. someone help me?

slate swan
#

nothing, im still trying to learn python

#

that's why i need help

cloud dawn
#

What do you need help with?

slate swan
#

coding it

#

a bot that replies to messages

#

if they say a command

boreal walrus
#

maybe start by learning the basics of python and work your way up

cloud dawn
slate swan
#

i know but this is myy last hope

cloud dawn
slate swan
#

yes

boreal walrus
#

lol

potent spear
#

learning Python while coding a bot is a steep learning curve

slate swan
#

ik but its for my server

slate swan
boreal walrus
potent spear
cloud dawn
slate swan
potent spear
slate swan
#

yes, neither replit or python

potent spear
#

?

slate swan
#

host like running?

potent spear
#

mhm

slate swan
#

if i got the code i would run it on python windows or replit

potent spear
#

python windows? so you'll be selfhosting?

cloud dawn
#

What do you guys think about guilded?

slate swan
potent spear
#

that's... obvious

slate swan
#

to make sure bot doesn't have problems

slate swan
potent spear
#

that you'd selfhost when testing...

slate swan
#

i don't understand sorry

potent spear
#

no worries

slate swan
# potent spear print table[1]for me also its type pls
Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 165, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 96, in warns
    em.add_field(name=f"Warning {warnnum}", value=f"Reason: {table[0]} | Date: <t:{int(table[1])}:F>")
ValueError: invalid literal for int() with base 10: 'o'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 605, in on_command_error
    raise error
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1382, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 948, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 174, in wrapped
    raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: invalid literal for int() with base 10: 'o'```
potent spear
potent spear
#

yeah, ABOVE the add field 🧠

#

with some newlines in between or whatever, I also needed the type

boreal walrus
#

oof

slate swan
potent spear
#

type?

slate swan
potent spear
glad cradle
potent spear
#

you can never be too sure with these kind of screenshots

slate swan
potent spear
slate swan
#

do i change the int to str

potent spear
slate swan
#

if they have 0 warnings yes

potent spear
#

what does it look like in your db?

#

what does your table create look like?

slate swan
slate swan
potent spear
slate swan
#

yeah

potent spear
#

can't you just look at it like so

#

through DB Browser or whatever

slate swan
potent spear
#

yup, that's great

#

so this means the time isn't fetched correctly, right?
since there's not a single column where the time is empty, right?

slate swan
#

i think yes

potent spear
#

can you also see the warning nr?

#

so you can actually show me what row you're fetching

slate swan
#

like the create table?

potent spear
#

no

#

I might also suggest to you to use

#
self._conn = await aiosqlite.connect(DATABASE_PATH)
self._conn.row_factory = aiosqlite.Row # <--- look at this line```
#

a rowfactory

slate swan
#

data = await cursor.fetchone()
if data:
em = nextcord.Embed(title=f"{member.name}#{member.discriminator}'s Warnings", color=0x99a2d1)
warnnum = 0
for table in data:
warnnum += 1
print(f"table: {table}\n{table[1]}, type: {type(table[1])}")
em.add_field(name=f"Warning {warnnum}", value=f"Reason: {table[0]} | Date: <t:{int(table[1])}:F>")

potent spear
#

that way, you can access columns in a db like you would with a dict
example
table['time'] instead of table[0]

#

so the self._conn is probably something else in your case

#

probably self.db or whatever

slate swan
#

but like

#

it should be 0

potent spear