#discord-bots

1 messages · Page 269 of 1

slate swan
#

you are supposed to call this method on bluepeint

young dagger
#

I have been struggling with this for a few hours now

chrome veldt
#

so like this instead

slate swan
young dagger
#

Cannot find reference 'edit_message' in '() -> InteractionResponse' Cannot find reference 'send_message' in '() -> InteractionResponse' Cannot find reference 'send_message' in '() -> InteractionResponse'

slate swan
#

its a problem with pycharm that it cannot read typehints properly if you have actual traceback come back

slate swan
young dagger
slate swan
#

so it is warning you

#

but you assign it when sending message

stark socket
#

im using a file.pkl to store object data
when i try to read what i stored without closing the python script it works

the problem is when i stop the python script and i start it again it should load the data from the file from the last session but is not reading any data despite it being there

young dagger
slate swan
young dagger
slate swan
#
class Counter(discord.ui.View):
    message: discord.Message
    ...
young dagger
young dagger
slate swan
#

..

#

but where show maybe some more code

young dagger
slate swan
young dagger
#

Yes, it disappeared

chrome veldt
#

ok these errors are breaking my brain

slate swan
#

which?
🤔

chrome veldt
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

chrome veldt
slate swan
#

well you are trying to send empty message

#

thats it

chrome veldt
#

yes i know but every little thing i do doesn't work

slate swan
#

show code then

chrome veldt
#

even tho it shouldnt be empty

#

ive checked

slate swan
#

blueprint.read() this wont work

#

!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.11)") object.

New in version 1.1.
slate swan
#

its awaitable as you can see

#

bot = commands.Bot(command_prefix=commands.when_mentioned_or("!"), intents=discord.Intents.all()) why you create a Bot instance if you literally created a subclass

chrome veldt
#

i am not a expert i just followed the guides

chrome veldt
slate swan
#

like any other awaitable function

#

await something()

chrome veldt
#

stats(str(await discord.Attachment.read(blueprint)))

slate swan
chrome veldt
#

got it working finally

slate swan
#

Nice

#

You mind sharing what this blueprint is for?

chrome veldt
#

also how do i get slash commands

slate swan
#

Button labels can be custom emojis right?

#

If so, is the syntax not <:emojiname:ID>

chrome veldt
#

is it just @client.tree.command() instead of @bot.command()

slate swan
#

!d discord.ui.Button

unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.

New in version 2.0.
slate swan
#

emoji kwarg ^

slate swan
#

!d discord.PartialEmoji.from_str

unkempt canyonBOT
#

classmethod from_str(value)```
Converts a Discord string representation of an emoji to a [`PartialEmoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PartialEmoji "discord.PartialEmoji").

The formats accepted are...
slate swan
#

I'm just using this, fine no?

sour cloak
#

so how do i make the bot to return failled response when room id is incorrect

swift trench
#
        with open("admins.txt", "r") as f:
          if str(ctx.user.id) in f.lines().split():
            admin = 'True'
          else:
            admin = 'False'
Traceback (most recent call last):
  File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 828, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 53, in setup
    if str(ctx.user.id) in f.lines().split():
AttributeError: '_io.TextIOWrapper' object has no attribute 'lines'

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

Traceback (most recent call last):
  File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'account' raised an exception: AttributeError: '_io.TextIOWrapper' object has no attribute 'lines'
#

anyone know why this doesnt work

twilit grotto
swift trench
#

Idk what that is

sick birch
# swift trench Idk what that is

Booleans are a special type of value that can be either True or False

        with open("admins.txt", "r") as f:
          if str(ctx.user.id) in f.lines().split():
            admin = 'True'
          else:
            admin = 'False'

Can be compressed into

with open("admins.txt", "r") as f:
  admin = str(ctx.user.id) in f.lines().split()
swift trench
#

oh I see now

#
        with open("admins.txt", "r") as f:
          admin = str(ctx.user.id) in f.lines().split()
        embed.add_field(name='Admin', value=admin, inline=True)
        await ctx.response.send_message(embed=embed)
#

gives me an error @sick birch

#
Traceback (most recent call last):
  File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 828, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 57, in setup
    admin = str(ctx.user.id) in f.lines().split()
AttributeError: '_io.TextIOWrapper' object has no attribute 'lines'

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

Traceback (most recent call last):
  File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'account' raised an exception: AttributeError: '_io.TextIOWrapper' object has no attribute 'lines'

swift trench
#

did not work

#
@client.tree.command(name='account', description='view your account')
async def setup(ctx: discord.Interaction):
  async with aiosqlite.connect("main.db") as db:
    async with db.cursor() as cursor:
      await cursor.execute('SELECT 1 FROM users WHERE memberid = ? AND guildid = ?', (ctx.user.id, ctx.guild.id,))
      data = await cursor.fetchone()
      if data:
        await cursor.execute('SELECT coins FROM users WHERE memberid = ? AND guildid = ?', (ctx.user.id, ctx.guild.id,))
        (coins,) = await cursor.fetchone()
        embed = discord.Embed(title=f"{ctx.user}'s Account")
        embed.add_field(name='Coins', value=coins, inline=True)
        with open("admins.txt", "r") as f:
          admin = str(ctx.user.id) in f.readlines()
        embed.add_field(name='Admin', value=admin, inline=True)
        await ctx.response.send_message(embed=embed)
      else:
        await cursor.execute("INSERT INTO users(memberid, guildid, coins) VALUES (?, ?, ?)", (ctx.user.id, ctx.guild.id, 100))
        await ctx.response.send_message("Account made!")
    await db.commit()
#

this is my full code

vocal snow
#

readlines() will include the trailing newline of each line

swift trench
#

Soooo

vocal snow
#

So you're comparing "100" to "100\n"

#

Hence it will always be False

#

Either read() and split on newline or add the newline to the id

keen dust
#

Hey guys I had a question about interactions in nextcord and discord. Is nextcord.Interaction or discord.Interaction limited only to slash commands or can it be used for prefix commands as well?

naive briar
#

It's only for interaction stuff, like app commands, buttons, drop-downs, ...

keen dust
#

yes that I know

#

but I'm talking about prefix and slash commands

naive briar
#

Already said it

#

Only for interaction stuff, no prefix commands

turbid condor
keen dust
turbid condor
#

Yes

keen dust
#

well thats the issue

#

for me it does work

#

its not supposed to

tawny junco
#

I wrote a basic code that gives or removes roles in a server and it works in 1 server but doesn't work in another. It has the same permissions in both servers but the error code says "missing permissions". What da heck?

turbid condor
#

Tbh hybrid commands also categories as slash commands so it might work for them

naive briar
turbid condor
tawny junco
# tawny junco I wrote a basic code that gives or removes roles in a server and it works in 1 s...

This is the code. But it works perfectly fine in another server so it's a permissions problem or whatever. Which also makes no sense.

role_name = "Voice Chat"
role_emoji = "🎤"
message_id = 1128780883340578976

@bot.event
async def on_raw_reaction_add(payload):
    guild = discord.utils.find(lambda g: g.id == payload.guild_id, bot.guilds)
    
    if payload.emoji.name == role_emoji and payload.message_id == message_id:
        role = discord.utils.get(guild.roles, name=role_name)
        print(role, type(role))
        if role:
            member = discord.utils.find(lambda m: m.id == payload.user_id, guild.members)
            print(member, type(member))
            if member:
                try:
                    await member.add_roles(role)
                except Exception as e:
                    print(e)
tawny junco
turbid condor
tawny junco
keen dust
#

for sending the message

tawny junco
#

Or vise versa

idle surge
#

Hey, im trying to send a auto message but having trouble. Dont know how to start the loop. This is what I have.

@tasks.loop(seconds=10)
async def auto_send():
    channel = vini.get_channel(1123454159543357540)
    embed = discord.Embed(colour=0x182D9F)
    embed.set_author(name="Just Some Subtle Reminders")
    embed.description = f"-n Be sure to use `.register` to register yourself to earn **Raneon** and buy **rewards**! \n *Do .help in #┃commands \n \n Learn how to join our team over here #┃how-to-join"
    embed.set_image(url="https://cdn.discordapp.com/attachments/1074138997498052760/1125310614147973130/HEADER_22.png")
    await channel.send(embed=embed, delete_after=60)
keen dust
#
@bot.command()
async def hello(interaction: discord.Interaction):
    await interaction.send("hi")
turbid condor
naive briar
tawny junco
#

How do I make the bot the higher hierarchy @turbid condor

naive briar
#

The interaction argument is actually a discord.ext.commands.Context

turbid condor
tawny junco
#

Sorry, slow responder here

turbid condor
keen dust
naive briar
#

That's because it's actually a context object, just print it

keen dust
#

I got the first part, thanks for the answer

tawny junco
turbid condor
tawny junco
#

I tried

#

It was stubbornly going back

#

So I deleted it and remade it

#

And now it's on the bottom

turbid condor
#

You sure u were saving it

tawny junco
#

The reorder button right? Yes I clicked save and everything

#

Maybe it was glitched or something

#

Btw thx for the help

#

I was about to blow my brains out

#

Last resort was administrator permissions

turbid condor
tawny junco
#

Damn

turbid condor
#

Since your bot would still been lower in hierarchy

marble wasp
#
class AutomaticModal(ui.Modal, title="Support"):
    def __init__(self):
        super().__init__()
        
    issue = ui.TextInput(label="What is your issue?", placeholder="Please describe your issue here in as much details as possible!", style=discord.TextStyle.long)
    
    async def on_submit(self, interaction: discord.Interaction):

        embed=discord.Embed(title=" ", description="Our bot wasn't able to locate a solution to this problem. If you would still like support on this issue, please create a ticket describing your issue!", color=discord.Color.red())

        await interaction.response.send_message(embed=embed, ephemeral=True, view=Button())```

using this code, if for example someones issue = "asd" how would i make the bot respond with a different message rather than the default message? is this possible
tawny junco
#

That's bull

turbid condor
tawny junco
#

Hey, is it possible to have a function that's basically the opposite of on_ready ? Like it would do a final command before the bot shuts down

idle surge
turbid condor
swift trench
#
      if data:
        await cursor.execute('SELECT coins FROM users WHERE memberid = ? AND guildid = ?', (user.id, ctx.guild.id,))
        (coins,) = await cursor.fetchone()
        coins = await cursor.fetchone[int(0)]
        coins = coins - rcoins
        embed = discord.Embed(title='Coins Removed')
        embed.add_field(name='Coins Removed', value=rcoins, inline=True)
        embed.add_field(name='Coins', value=coins, inline=True)       
        embed.add_field(name='Author', value=ctx.user.id, inline=True)
        await ctx.response.send_message(embed=embed)
        await cursor.execute("INSERT INTO users(memberid, guildid, coins) VALUES (?, ?, ?)", (user.id, ctx.guild.id, coins))
#

how do I remove the coins?

#
Traceback (most recent call last):
  File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 828, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 75, in removecoins
    coins = await cursor.fetchone[int(0)]
TypeError: 'method' object is not subscriptable

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

Traceback (most recent call last):
  File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/zio-accounts/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 842, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'remove-coins' raised an exception: TypeError: 'method' object is not subscriptable
naive briar
tawny junco
#

Thx @turbid condor and @vocal snow I will experiment now

hasty coral
#

Is there a way to bypass the 1024 character limit for an embed? It’s for a server info command

naive briar
#

No

turbid condor
#

hasn't the character limit been increased now?

turbid condor
sick birch
hasty coral
slate swan
hasty coral
#

This is the code I’m using, is there a way I can alter it so that it doesn’t exceed the embed limit?

        emoji_list = ' '.join(str(emoji) for emoji in emojis)
        embed.add_field(name='Emojis', value=emoji_list, inline=False)
    else:
        embed.add_field(name='Emojis', value='No emojis in this server', inline=False)```
turbid condor
#

you can paginate the embed

#

so that it shows some emojis on first page and other on next

hasty coral
#

Ive found a way to list some of the emojis and then out a counter at the end of the message for example [emoji1][emoji2][emoji[3] +5
This shows the first set of emojis then calculates however many is left that aren't shown. However the code is listing the emojis below eachother even though ive set inline to false

#
        emoji_list = [str(emoji) for emoji in emojis[:15]]
        emoji_count = len(emojis)
        emoji_remaining = max(emoji_count - 15, 0)
        emoji_list_str = '\n'.join(emoji_list)
        emoji_list_str += f'\n... +{emoji_remaining}'
        embed.add_field(name='Emojis', value=emoji_list_str, inline=False)
    else:
        embed.add_field(name='Emojis', value='No emojis in this server', inline=False)```
#

wait i figured out why its listing them under eachother facepalm

turbid condor
idle surge
#

Hey, dropping my whole code here basically, so I basically am setting up a dropdown with different modals connecting to those dropdowns. I am just gonna show just one modal as its a lot. But basically when I run the command ".invite" nothing happens, no error.

#

Dropdown:

@vini.command()
@commands.has_permissions(administrator=True)
async def invite(ctx):
    embed1 = discord.Embed(colour=0x182D9F)
    embed1.set_author(name="Rane's Staff Application")
    embed1.description ='**Please click the dropdown and press on the role you are seeking to join as.**'
    embed1.set_image(url="https://media.discordapp.net/attachments/991482958026379274/1123479665391177908/THEAPPLY.png?width=1440&height=323")
    await ctx.send(embed=embed1, view=InviterView())

class Inviter(discord.ui.Select):
    def __init__(self):
       options=[
           discord.SelectOption(label="Staff", custom_id="staff"),
           discord.SelectOption(label="Player", custom_id="player"),
           discord.SelectOption(label="Studios", custom_id="studios"),
           discord.SelectOption(label="Content Creator", custom_id="content")
       ]
       super().__init__(placeholder="What game are you playing?", options=options, min_values=1, max_values=1)
    async def callback(self, interaction: discord.Interaction):
        channel = vini.get_channel(1123456106740584528)
        guild = vini.get_guild(1123453068952993802)
        if interaction.custom_id == "staff":
            modal1 = staff_modal()
            await interaction.response.send_modal(modal1)
            await modal1.wait()
        elif interaction.custom_id == "player":
            modal3 = player_modal()
            await interaction.response.send_modal(modal3)
            await modal3.wait()
        elif interaction.custom_id == "studios":
            modal4 = studios_modal()
            await interaction.response.send_modal(modal4)
            await modal4.wait()
        elif interaction.custom_id == "content":
            modal5 = content_modal()
            await interaction.response.send_modal(modal5)
            await modal5.wait()

class InviterView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
        self.add_item(Inviter())
#

Im actually just not gonna show the modal as I know thats not the issue at hand

#

Its just having issues showing the view.

naive briar
idle surge
twilit grotto
turbid condor
#

Can u show the buttons u created and how are u sending them

#

I mean your code

ember mango
#

Why Errol?

#

Same

shrewd fjord
ember mango
twilit grotto
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

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

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

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

shrewd fjord
ember mango
twilit grotto
#

if it isn't that, just make sure ur bot has high permissions (or good enough permissions)

twilit grotto
shrewd fjord
#

i dont think you need any intents for creating slash commands tho

#

not sure

twilit grotto
#

iirc you do, not entirely sure

naive briar
#

What will it be then

ember mango
#

Now i create prefix?

shrewd fjord
naive briar
vale wing
ember mango
#

ANSWER ME💀💀

shrewd fjord
naive briar
ember mango
shrewd fjord
#

ended rn but prac exams are still going on

ember mango
#

@shrewd fjord
Help me?

naive briar
#

That explains it

shrewd fjord
#

!d disnake.Interaction

unkempt canyonBOT
#

class disnake.Interaction```
A base class representing a user-initiated Discord interaction.

An interaction happens when a user performs an action that the client needs to be notified of. Current examples are application commands and components.

New in version 2.0.
vale wing
# ember mango
  1. Your bot isn't in provided server
  2. Bot was not authorised with applications.commands scope in that server
shrewd fjord
#

just telling about wht can happen next

shrewd fjord
#

kick the bot

ember mango
shrewd fjord
#

if you have invited without appcommands scope already

vale wing
#

Authorise it again but with that scope

ember mango
#

Waite

shrewd fjord
#

then copy the link and invite again

shrewd fjord
vale wing
#

We need promotion

ember mango
vale wing
#

There are plans but why waste efforts for nothing

shrewd fjord
#

ohk

shrewd fjord
ember mango
#

Same error

#

Which one is wrong?

shrewd fjord
ember mango
shrewd fjord
ember mango
shrewd fjord
#

use InteractionBot if you dont want prefix

ember mango
#

Inter?

shrewd fjord
#

have to check docs

ember mango
#

Where?

turbid condor
#

wait is your bot even in the guild for which you are trying to sync command

turbid condor
#

nope i know nothing but disnake

vale wing
# shrewd fjord

I actually managed to contact a 100k youtuber (whirow to be precise) but he said he's not going to make vid on it 😭

shrewd fjord
ember mango
#

Ok

vale wing
shrewd fjord
ember mango
#

Right?

vale wing
#

Ig we need to target a lot of smaller youtubers

shrewd fjord
shrewd fjord
vale wing
#

You're right actually

#

We ain't monetising the bot

ember mango
vale wing
#

Cause not enough servers

shrewd fjord
#

mhm

vale wing
#

Stupid circle

shrewd fjord
#

maybe add some cool premium commands ig

ember mango
vale wing
#

I was planning to do that after site, but site is after 500 servers

shrewd fjord
shrewd fjord
ember mango
shrewd fjord
ember mango
shrewd fjord
#

i think, i mean not about the site, about premium cmd

vale wing
#

They are easy to do

ember mango
shrewd fjord
vale wing
#

The monetisation itself is difficult cause we need a site, security and payment processor

#

Me being in Russia makes things even more difficult

shrewd fjord
ember mango
vale wing
#

FREEBOBUX promocode

#

☺️

shrewd fjord
shrewd fjord
vale wing
#

Only 40 servers in half of year

shrewd fjord
#

are you using virtual environment?

#

use then...

#

python -m venv .venv

#

this should create a virtual environment for you

#

............. um did you activate venv?

#

!venv

unkempt canyonBOT
#
Virtual environments

Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.

To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)

Then, to activate the new virtual environment:

Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate

Packages can then be installed to the virtual environment using pip, as normal.

For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.

Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.

Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
shrewd fjord
#

and this shouldnt show any error

#

actually there aint good free host

#

mhm...

#

may try OceanHost or something

#

let me try

#

its ip is used anyway

#

not good for your bot

turbid condor
#
Time4VPS

Affordable and powerful VPS Hosting in Europe. Linux, Windows and Storage VPS available from 1.99 EUR/month.

shrewd fjord
#

!host

unkempt canyonBOT
#
Discord Bot Hosting

Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.

See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.

You may also use #965291480992321536 to discuss different discord bot hosting options.

verbal hawk
#

Hi!
I'm making a discord giveaway bot but I'm having problems getting the users who reacted to the giveaway embed. I have the ID of the embed, and I'm 100% sure it is right since the bot can react to it, however gwmessage.reactions gives an empty list, even when I and the bot have reacted to it as well.
Here's my relevant piece of code:

            await gwmessage.add_reaction(":tada:")

            await asyncio.sleep(delta.total_seconds())

            print(gwmessage.reactions)    
            reaction_users = gwmessage.reactions[0].users().flatten()
            reaction_users.pop(reaction_users.index(bot))

It was giving me an IndexError, so I printed gwmessage.reactions and it is empty. Any clues why that would be?

upbeat gust
#

If so, it's because you're using outdated code

verbal hawk
#

yes, since reaction_users is empty

verbal hawk
upbeat gust
verbal hawk
#

yes, I'm using intents = discord.Intents.all()

upbeat gust
#

how are you getting gwmessage

verbal hawk
#

they are all enabled in the dev portal as well

verbal hawk
# upbeat gust how are you getting `gwmessage`
async for message in interaction.channel.history():
                if not message.embeds:
                    continue
                if message.embeds[0].title == embed.title and message.embeds[0].colour == embed.colour:
                    gwmessage = message
                    break

I know gwmessage is the right message, since await gwmessage.add_reaction(":tada:") works and puts the reaction onto the right message

upbeat gust
#

you need to fetch the message to get the updated stuff

#

await interaction.channel.fetch_message(gwmessage.id)

turbid condor
#

welp wouldn't using buttons and a database would make it look better?

upbeat gust
#

It would

verbal hawk
#

it certainly would, I'm planning on rewriting that part soon, for now though I want to get the basics right, and I also hate working with buttons lmao

verbal hawk
turbid condor
#

welp u can try alternate approach of storing the ids of the ppl who react to the msg too instead of checking who made a reaction since the reactions can be removed by some one who has perms and can also get deleted whereas incase of storing them this problem would not occur

verbal hawk
turbid condor
#

welp why would one join a giveaway if he has to opt out?

verbal hawk
#

I don't know, but it's much more straightforward for end users this way

turbid condor
#

I am just giving a suggestion it all depends on you in the end since you are coding

verbal hawk
#

yea ty this project is far from being finished lol so this is not it's final form

turbid condor
verbal hawk
upbeat gust
#

You need to do something like this (this is on the official docs, theres always great examples)

verbal hawk
# upbeat gust

but where is the message defined in this example? what message does reaction.users() use for getting them?

upbeat gust
#

gwmessage.reactions[0].users()

verbal hawk
#

ooh I see, thank you!

wise plume
#

Hey, how can I mention @everyone?

thin raft
wise plume
#

can i mention @everyone in embed?

upbeat gust
#

It won't ping

turbid condor
#

Only description

wise plume
#

okay

#

so description="@everyone"

#

and thats it?

turbid condor
#

Yeah should work

quick gust
#

I dont think that pings them

#

it only pings if its in the message content

#

as chrispy said

ember mango
#

Hello anyone Can Fix this Why Just Select One?

naive briar
#

The embed variable you made is static, it will never change if you don't make it so

naive briar
#

Fix what

ember mango
naive briar
#

What does that even mean

turbid condor
#

Do you mean it should send a random answer?

ember mango
#

I mean how to fix random answers

#

Look why just select one

#

I mean select random

dusty drift
#

yo, how to fix this error?
startswith first arg must be str or a tuple of str, not bytes
i am getting it while creating webhook with custom avatar

ember mango
#

Please Help me

turbid condor
#

And u want it to send 3 different embeds or just option

slate swan
#

move it inside so it is choosing random on each command call

turbid condor
#

And traceback too

dusty drift
slate swan
#

error?

naive briar
#

!tracrback

slate swan
#

full traceback not just message

naive briar
#

!traceback

unkempt canyonBOT
#
Traceback

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

A full traceback could look like:

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

If the traceback is long, use our pastebin.

tight mica
#

The avatar needs to be a bytes object, not a string

#

why not just directly use image_bytes as avatar instead of saving it

naive briar
#

Great, they're using requests and aiohttp together

tight mica
#

bruh

slate swan
#

!blocking skull

unkempt canyonBOT
#
Asynchronous programming

Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

slate swan
#

long ass embed

tight mica
#

cringe

slate swan
#

aiohttp my beloved

grand moss
#

idk why I'm getting this

#

I think the 'play' is proper tho

naive briar
#

!yt

unkempt canyonBOT
#
Our youtube-dl, or equivalents, policy

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

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

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

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

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

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

ah

chrome veldt
#

why do i put heres i forgot

tall temple
#

pls how can i delete all file content ?

meager chasm
#

A file as in an attachment?

#

You want to delete the files of a message without deleting the content?

tall temple
#

in your desktop

meager chasm
#

this is the discord bots channel, you should ask in #python-discussion or claim a help channel next time.
But to remove the data in a json file you can open it with open() in "w" mode, and just write "{}" to it

#

If you have worked with open() or files before I would suggest reading up on that first

tall temple
#

ok thx

meager chasm
tall temple
meager chasm
#

r+ is for reading then writing

#

if you just want to write empty json to it then you can use w directly

#

if you want to read then write then use r+

#

make sure to seek after reading

tall temple
#

okay but i can't read with w ?

meager chasm
#

no

tall temple
#

yeah that's the problem

#

i want to take infos from the file then delete file content and rewrite

meager chasm
#

ok

#

you can use r+ then

#

just seek after you read

#

file.seek(0)

tall temple
#

ok thx

chrome veldt
tall temple
#

@meager chasm something like that (without seek) ?

chrome veldt
#

idk why this error keeps happning even tho it worked befor

silk wasp
#

can see your def setup()?

chrome veldt
#

oh nvm had the wrong token

silk wasp
#

ok

meager chasm
tall temple
#

oh yeah my bad bcz i changed names

meager chasm
#

!with

unkempt canyonBOT
#
The `with` keyword

The with keyword triggers a context manager. Context managers automatically set up and take down data connections, or any other kind of object that implements the magic methods __enter__ and __exit__.

with open("test.txt", "r") as file:
    do_things(file)

The above code automatically closes file when the with block exits, so you never have to manually do a file.close(). Most connection types, including file readers and database connections, support this.

For more information, read the official docs, watch Corey Schafer's context manager video, or see PEP 343.

meager chasm
#

try to use open like this

#

so it will close the file for you

tall temple
#

yeah ik

#

👌

#

@meager chasm could you help me with that case please ? :

    with open("vouches.json", "r") as filer :
        jsoncontent = filer.read()
        vouchesl = json.loads(jsoncontent)

    vouchesl.append(f"**Submitted feedback by {ctx.author.name}**\n\n> **Product** ・ `{product}`\n> **Seller** ・ <@>\n> **Service rate** ・ `{rate} / ⭐⭐⭐⭐⭐`\n> **Feedback** ・ `{feedback}`")
    with open("vouches.json", "w") as filew :
        filew.write("")
        json.dump(vouchesl, filew)```
#
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 982, in _invoke
    await self.callback(ctx, **kwargs)
  File "f:\mesdraps\vouches_bot\main.py", line 38, in feedback
    vouchesl = json.loads(jsoncontent)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1)

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

Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: JSONDecodeError: Expecting value: line 1 column 2 (char 1)
chrome veldt
#

how can i return a file

#

like a image

meager chasm
#

Write an empty json object

#

Like {}

#

And make sure your json is valid before you read it

tall temple
#

okay

sick coyote
#

if i provide a emoji to my command, it just returns the emoji id like :abc:
how can i get the asset?

sick coyote
#

nah i need to get the asset to convert it into bytes

tall temple
#

ah

copper gulch
#

ctx.guild.region
does this still exists?

#

its not working for me anymore

#

like it has been changed\

sick coyote
#

its deprecated

chrome veldt
#

how do i send a image?

#

(in terms of a bot)

fiery jetty
chrome veldt
#

thx

#

love this bot

slate swan
chrome veldt
#

how do i give a description to a argument

slate swan
#

what library?

chrome veldt
slate swan
#

this tells me nothing

chrome veldt
slate swan
#

you pass it to bot.command()

#

!d discord.ext.commands.Bot.command

unkempt canyonBOT
#

@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
slate swan
#

you just say description="idk"

grand moss
#

how can I make it read the url
The [0][url] doesn't work as url is more than one character. Just l also doesn't work
[{"id":"7jk","url":"https://cdn2.thecatapi.com/images/7jk.png","width":638,"height":478}]

slate swan
#

[{"id":"7jk","url":"https://cdn2.thecatapi.com/images/7jk.png","width":638,"height":478}] this is what get_cat returns?

grand moss
#

yes

#
async def get_cat():
  async with aiohttp.ClientSession() as session:
    async with session.get("https://api.thecatapi.com/v1/images/search") as image:
      if image.status == 200:
        json_data = await image.json()
      
        return json_data 
slate swan
unkempt canyonBOT
#

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

https://cdn2.thecatapi.com/images/7jk.png
grand moss
#
Traceback (most recent call last):
  File "/home/runner/PyBot-Test-2/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 135, in cat
    embed.set_image(kitty[0]["url"])
TypeError: Embed.set_image() takes 1 positional argument but 2 were given

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

Traceback (most recent call last):
  File "/home/runner/PyBot-Test-2/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/PyBot-Test-2/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/PyBot-Test-2/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Embed.set_image() takes 1 positional argument but 2 were given
slate swan
#

!d discord.Embed.set_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
#

url is keyword only

grand moss
#

OH

#

lemme try another way

slate swan
grand moss
#

not sure but I think I can assign [0][url] to a variable and pass that variable as a parameter

slate swan
#

nope

#

you can do it directly in the set_image

#

thats not what is wrong

#

if the argument is keyword only it means that:

# wont work

my_function(argument) # positional

# will work

my_function(argument=argument) # key-word
``` see the difference?
grand moss
#

ahh

grand moss
#

is there a way to obtain the epoch time when the command was executed?

potent spear
grand moss
#

I don't know how

#

I wanted the footer in my embed to show <t:1689275955:F>

slate swan
unkempt canyonBOT
#

classmethod datetime.now(tz=None)```
Return the current local date and time.

If optional argument *tz* is `None` or not specified, this is like [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today"), but, if possible, supplies more precision than can be gotten from going through a [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time") timestamp (for example, this may be possible on platforms supplying the C `gettimeofday()` function).

If *tz* is not `None`, it must be an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass, and the current date and time are converted to *tz*’s time zone.

This function is preferred over [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today") and [`utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "datetime.datetime.utcnow").
potent spear
#

example

import discord
import datetime as dt

current_time = dt.datetime.now()
some_format = discord.utils.format_dt(current_time, style="F")```
slate swan
#

style is keyword only

#

!d discord.utils.MISSING

unkempt canyonBOT
#

discord.utils.MISSING```
A type safe sentinel used in the library to represent something as missing. Used to distinguish from `None` values.

New in version 2.0.
grand moss
potent spear
slate swan
grand moss
#

thanks I'll check it out

potent spear
potent spear
slate swan
potent spear
#

so why doesn't it basically = "f" ?

slate swan
unkempt canyonBOT
#

discord/utils.py lines 1236 to 1238

if style is None:
    return f'<t:{int(dt.timestamp())}>'
return f'<t:{int(dt.timestamp())}:{style}>'```
potent spear
unkempt canyonBOT
#

src/env.py line 14

default: t.Any = MISSING```
slate swan
#

i use the same logic in my bot

#

"bot" it does not exist yet

idle surge
slate swan
left dew
#

i’m wanting to store the inputted values from a modal that can be submitted multiple times so that i can use the inputted information later. but i’m not sure how to store it and how to store the values if the nodal has been answered more than once

slate swan
#

and MISSING comes in clutch

potent spear
#

ah, wow

#

it's basically a value with no specific meaning
hence when used, it'll error... (and None wouldn't, as it could be a valid value)

slate swan
#

yeah something like that

potent spear
#

so it's more like a placeholder?

slate swan
#

its like actual None

potent spear
#

mhm, I see
I'd have to find use cases for that in my code

final drum
#

Hello, I am trying to make a blackjack discord bot for my server. I have spent the last few hours learning and coding the bot and am encountering an issue with BREAK. Does anyone have many solutions or recommendations?

slate swan
#

you are outside a while loop you defined above already

final drum
slate swan
#

On discord bots, is it possible for discord.py to register a command like "/token" and then it will ask for a bot token and instead of the bot using say for example "TRXNCHES BOT" it will now be online on "NEW USER BOT" and it host that bot? or is that not possible, i know its possible for discord.js but im not sure about discord.py

slate swan
slate swan
slate swan
slate swan
slate swan
slate swan
#

What do you mean?

#

Are you trying to check if a user has nitro?

slate swan
#

no, i'm trying to create a slash command that can register a bot token and then bring the given token online hosting the bot.

#

What part are you stumped on

#

anywhere i can see on the docs about this

#

you want to create a new bot with that token?

slate swan
#

yeah that isn't hard to do, but the bot would have no commands

slate swan
#

I don't know of a way to do that, I was thinking you'd have to create multiple instances of the bot class then update those with the new tokens, @slate swan do you know?

#

no idea never tried to

#

Yeah I don't really know sorry, @slate swan

#

It's possible but it's gonna be more complex than I thought

#

ty

#

for the help!

ember mango
#

Anyone Can help me Why Didn't Change?

#

Note: disnake

slate swan
#

already did above but let me say it again:

  • you are choosing the random item outside the command
  • do it inside so it gets choosen on each command run
slow fog
#

unless you have it to be inside a loop

#

then its value will change

slate swan
#

!e ```py
import random

random_number = random.randint(1, 10)

def get_random_number():
print(random_number)

get_random_number()
get_random_number()
get_random_number()
get_random_number()
get_random_number()

unkempt canyonBOT
#

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

001 | 2
002 | 2
003 | 2
004 | 2
005 | 2
slate swan
#

!e ```py
import random

def get_random_number():
random_number = random.randint(1, 10)
print(random_number)

get_random_number()
get_random_number()
get_random_number()
get_random_number()
get_random_number()

unkempt canyonBOT
#

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

001 | 8
002 | 7
003 | 1
004 | 9
005 | 3
slate swan
#

i hope you see difference

ember mango
slate swan
#

you literally have example above your message

slow fog
#

lol

ember mango
slate swan
#

so what you want

#

you are asking why the thing you are choosing randomly dont change on each command ran dont you

#

and i shown you why

slate swan
#

what you mean by that?

slow fog
#

send your code

ember mango
#

You said print (random_number)
Where should I embed

#

Await ctx.send(embed=embed)

slate swan
#

obviously i wont give you straight example you can copy paste and make it work

plucky sun
#

Hi, can someone help me. I have a problem with the select menus, only the first one works and the second one doesn't even give an error, only 'This interaction failed' .

  ```  select = self.children[0]
    select.disabled = True
    if "title" in select.values:
            await interaction.response.send_message('Test :D (Title)')

    if "decs" in select.values:
            await interaction.response.send_message('Test :D 2 (Description)')```
#

@slate swan

slate swan
#

full code

plucky sun
#

Can I send it tomorrow?

slate swan
#

you can do whatever you want

ember mango
#

When i Again command
He created a new embed why?

slate swan
ember mango
slate swan
#

how am i supposed to know when you dont even share the code

slate swan
#

and where you define embed?

ember mango
slate swan
ember mango
#

I fixed

#

Thank you man ❤️

#

I embed died into the function so it was fixed

slate swan
#

👍

#

glad you understand

ember mango
tall temple
#

nothing occurs when i click on validation button

idle surge
naive briar
unkempt canyonBOT
#
Formatting code on discord

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.

For long code samples, you can use our pastebin.

naive briar
hushed galleon
#

!d discord.ui.Select.values

unkempt canyonBOT
hushed galleon
#

hmm that is pretty lacking of an explanation

idle surge
#

lol okay, thank you.

idle surge
# hushed galleon custom IDs in the context of discord's API are only to identify a single compone...

Do you also know how I could setup the if statement? I did interaction.value but the attribute isn't valid.

class Inviter(discord.ui.Select):
    def __init__(self):
       options=[
           discord.SelectOption(label="Staff", value="staff"),
           discord.SelectOption(label="Player", value="player"),
           discord.SelectOption(label="Studios", value="studios"),
           discord.SelectOption(label="Content Creator", value="content")
       ]
       super().__init__(placeholder="What game are you playing?", options=options, min_values=1, max_values=1)
    async def callback(self, interaction: discord.Interaction):
        channel = vini.get_channel(1123456106740584528)
        guild = vini.get_guild(1123453068952993802)
        if interaction.value == "staff":
            modal1 = staff_modal()
            await interaction.response.send_modal(modal1)
            await modal1.wait()
        elif interaction.value == "player":
            modal3 = player_modal()
            await interaction.response.send_modal(modal3)
            await modal3.wait()
        etc...
hushed galleon
#

values (plural) is an attribute of the Select class which returns a list, and since you're inside a method of a Select subclass you should write self.values[0] to retrieve the first value

slate swan
#

Hello

#
from discord.ext import commands
import discord
from colorama import Fore
from keep_alive import keep_alive
from os import environ
import json

bot = commands.Bot("!", self_bot=True) # Defining bot.

@bot.event # Turning the bot online.
async def on_ready():
    print("This program has logged in to the account " + Fore.YELLOW + f"{bot.user}.\n")
    with open("data.json", "r") as f:
        data = json.load(f)
    if data["guild"] == None or data["channel"] == None:
        pass
    else:
        try:
            voice_channel = discord.utils.get(bot.get_guild(int(data["guild"])).channels, id = int(data["channel"]))
            await voice_channel.connect()
            print(f"{Fore.GREEN}[-]{Fore.WHITE} Connected to {Fore.CYAN}{voice_channel} {Fore.WHITE}in {Fore.CYAN}{voice_channel.guild}{Fore.WHITE}.")
        except:
            print(f"{Fore.RED} [ - ] Error Occured. Please reconnect using commands.")

@bot.command() # Join command.
async def join(ctx, voice_channel : discord.VoiceChannel):
    await voice_channel.connect()
    data = {"guild":str(ctx.guild.id),"channel":str(voice_channel.id)}
    with open("data.json", "w") as f:
        json.dump(data, f)
    print(f"{Fore.GREEN}[-]{Fore.WHITE} Connected to {Fore.CYAN}{voice_channel} {Fore.WHITE}in {Fore.CYAN}{voice_channel.guild}{Fore.WHITE}.")
    await ctx.message.delete()

@bot.command() # Leave command.
async def leave(ctx):
    voice_client = ctx.message.guild.voice_client
    await voice_client.disconnect()
    with open("data.json", "w") as f:
        json.dump({"guild":None,"channel":None}, f)
    print(f"{Fore.RED}[-]{Fore.WHITE} Disconnected from {Fore.CYAN}{voice_client.channel}{Fore.WHITE} in {Fore.CYAN}{ctx.message.guild}{Fore.WHITE}.")
    await ctx.message.delete()

keep_alive()
bot.run(environ["token"], bot=False) # Run the bot by adding your token in between the quotes.`````
winter hare
#

how would i use dicts for storing information about users who left and joined a VC?

slate swan
hushed galleon
slate swan
hushed galleon
#

hmm it might still be against rule 5 to ask specifically how a user account can prevent AFKing via automation, perhaps for a bot that would be fine (although im not familiar with it since i dont use vc bots)

hushed galleon
# winter hare how would i use dicts for storing information about users who left and joined a ...

this is a bit too vague as there's a lot of ways to use a dictionary, but for a simple bot a global variable is probably fine, for example: ```py

Storing voice channel ID -> number of joins

voice_join_counts = {}

bot = commands.Bot(...)

https://discordpy.readthedocs.io/en/stable/api.html#discord.on_voice_state_update

@bot.event
async def on_voice_state_update(member: discord.Member, before: discord.VoiceState, after: discord.VoiceState):
if before.channel is None and after.channel is not None:
channel_id = after.channel.id
current = voice_join_counts.get(channel_id, 0)
voice_join_counts[channel_id] = current + 1``` note of course that the dictionary will be lost once your bot restarts

winter hare
#

also do you have any links/docs about dicts?

hushed galleon
#

if by restricting access you mean modifying the channel permissions to disallow people from joining you could probably do that without a dictionary, although i think this might be limited by discord's strict channel edit ratelimits

winter hare
# hushed galleon if by restricting access you mean modifying the channel permissions to disallow ...

i tried something like this but don't know how i would make it to where only one person can use the command

    async def unlock(self, interaction:discord.Interaction):

        if interaction.user.voice is None:

            await interaction.response.send_message(content='You are not in a voice channel.')

        channel = interaction.user.voice.channel


        overwrite = channel.overwrites_for(interaction.guild.default_role)
        overwrite.connect = True

        await channel.set_permissions(interaction.guild.default_role, overwrite=overwrite)
        await interaction.response.send_message(content='VC has ben unlocked, members can now join the VC.')```
#

But I can already see that going bad

plucky sun
#

@turbid condor

turbid condor
#

What's the error?

plucky sun
# turbid condor What's the error?

Hi, can someone help me. I have a problem with the select menus, only the first one works and the second one doesn't even give an error, only 'This interaction failed' .

turbid condor
lofty lance
#

so i am facing a strange issue

#

i was testing my discord bot

#

and it workd fine
then i added it to the server where it need to do that job

#

and suddnly it stopd responding
and now even if i change the tokens
its not respondign

#

@turbid condor can u help pls

turbid condor
#

make sure your bot has the appropriate permissions in the server

#

and channels too

lofty lance
#

so i can say that yes ti has perms

turbid condor
#

just recheck it once

#

and then check your intents

slate swan
#

I set up a discord bot on my friends computer, when use the /command on my discord account on my pc, the command works fine. When my friend uses the command on his phone it works fine. But if he does the command on his computer where the bot is set up, the command doesnt respond and I get this error in the CMD

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

any idea why?

lofty lance
#

intents is set to all

turbid condor
turbid condor
lofty lance
#

all 3

turbid condor
#

and 1 more question did the bot worked after joining the guild it was supposed to be used in

lofty lance
#

it was working fine in testing guild

turbid condor
turbid condor
slate swan
# turbid condor can you show your code for usernames command
# LIST OF USERNAMES
@app_commands.command(name = "usernames", description="A List of PS4 Users & Folder ID's")

async def usernames(self, interaction: discord.Interaction) -> None:

    # READ DEFAULT VALUES
    with open(default_config, 'r') as f:
        ftpinfoBIG = f.read().splitlines()
        default_ip = ftpinfoBIG[10].replace(' ', '').replace('IP=', '')
        default_port = int(ftpinfoBIG[12].replace(' ', '').replace('Port=', ''))
    
    #CONNECT TO PS4
    ftp = FTP()
    ftp.connect(default_ip, default_port)
    ftp.login()
    ftp.cwd("/user/home/")
    data = []
    ftp.dir(data.append)
    
    # LIST OF USERS
    embed = discord.Embed(title=f"📑 __**LIST OF USER FOLDER ID'S**__", color=discord.Color.gold())
    embed.set_author(name= f'Thank you {interaction.user.name} calling list', icon_url= interaction.user.avatar)
    x = 1
    
    for line in data:
        # SKIP FIRST THREE DIRECTORY LISTINGS
        if x > 2:
            y = x - 2
            folderids = line.split(" ")[-1]
            ftp.cwd('/user/home/' + folderids)
            ftp.retrbinary("RETR " + 'username.dat' ,open('username.dat', 'wb').write)
            with open('username.dat', 'r') as moredetailsLOL:
                text_folderids  = moredetailsLOL.read().rstrip('\x00')
                text_folderids = text_folderids.split(" ")[-1]
            silentremove('username.dat')
            embed.add_field(name = str(y) + ") " + f'__{text_folderids}__' + ' = ' + f'**{folderids}**', value = '\u200b', inline=False) 
            
        x += 1
       
    embed.set_footer(text="Type /guide to see a list of features and commands available.")
    await interaction.response.send_message(embed=embed, ephemeral=False)
    ftp.quit()
lofty lance
slate swan
# turbid condor defer this command

so await interaction.response.defer() by itself in the beginning or middle of the code?
then `await interaction.followup.send for the final embed message?

lofty lance
#

pefect ig?

slate swan
turbid condor
#

and then change the interaction.response.send_message('.....') to interaction.followup.send('....')

lofty lance
#

it workd

#

wait

#

let me try it in test server i tried it in 3rd server

#

@turbid condor a sample code is working fine

turbid condor
lofty lance
#

but not if i apply the code it suppse to do task of

turbid condor
turbid condor
#

yes

lofty lance
#

oke give me a moment

slate swan
#

also you assign callback after you send the message

tall temple
#

fact, i found another solution but tysm @slate swan

plucky sun
#

how can i make it delete both mine and the bot message ? With this it does not happen.

        await interaction.response.delete()
        await message.delete()
#

@turbid condor

plucky sun
turbid condor
#

we mean where u defined message in your command?

plucky sun
turbid condor
#

what is message = ?? inside your code

plucky sun
#
            await interaction.channel.send('Please enter a title')
            message = await bot.wait_for('message', check=lambda m: m.author == interaction.user)
            self.title = message.content
            await interaction.response.delete()
            await message.delete()```
#

@turbid condor

turbid condor
#

ok so this deletes your message?

plucky sun
turbid condor
#

so assign a variable to the bot response and then delete it using the same way you deleted yours

tall temple
slate swan
#

No

tall temple
#

?

slate swan
#
if message.author.id == 123456789:
   # blah
tall temple
#

yeah my bad

plucky sun
#

can someone help me, in the slash command there is a channel: discord.Textchannel, I want to take it and go to the class and send the embed where the channel is given.

#

@turbid condor

#

@tall temple

vocal snow
#

Set the channel as an attribute in the _init_ then and use it when you need to send the embed

plucky sun
#

can you put it for me I don't know where

slate swan
#

!d discord.Embed.set_footer

unkempt canyonBOT
#

set_footer(*, text=None, icon_url=None)```
Sets the footer for the embed content.

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

I see no timestamp to give there

#

!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...
slate swan
#

timestamp kwarg

ember mango
#

How remove This
['']

#

My question Very Easy🥲

#

@slate swan Sorry ping

slate swan
#

thats how lists are represented

#

use str.join

#

!d str.join

unkempt canyonBOT
#

str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
ember mango
#

str.join (here name list)?

slate swan
#

no

#

!e ```py
my_list = ["a", "c", "b"]

print(", ".join(my_list))```

unkempt canyonBOT
#

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

a, c, b
ember mango
#

My list select random

slate swan
#

its for string like i said

#

then you can pass it to embed description or elsewhere

ember mango
slate swan
ember mango
#

I can't Paste In Add.failed

slate swan
#

i said description or elsewhere

ember mango
ember mango
thin raft
#

!code

unkempt canyonBOT
#
Formatting code on discord

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.

For long code samples, you can use our pastebin.

ember mango
#

emm.add_field(name="Below answers cup: ", value=f"{random_cups.join(random_cups)}", inline=False)
Here

slate swan
thin raft
young dagger
#

Does this look good?

# Get the list of member IDs in team 1 and team 2
team_1_member_ids = [user['member'].id for user in team_1]
team_2_member_ids = [user['member'].id for user in team_2]

# Update the last_activity field for all users in team 1 and team 2
await collection.update_many(
    {"discord_id": {"$in": team_1_member_ids + team_2_member_ids}},
    {"$set": {"last_activity": datetime.datetime.now()}}
)```
naive briar
#

Looping twice and concatenate, seems inefficient

slate swan
#

using .bulk_write could be better here

#
team_1_member_ids = [user['member'].id for user in team_1]
team_2_member_ids = [user['member'].id for user in team_2]
``` also this can be just this ```py
team_member_ids = [user['member'].id for user in team_1 + team_2]
naive briar
#

!d itertools.chain me when

unkempt canyonBOT
#

itertools.chain(*iterables)```
Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence. Roughly equivalent to:

```py
def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
slate swan
#

importing other library blahblahblah

young dagger
# slate swan using `.bulk_write` could be better here

Something like this?

    team_member_ids = [user['member'].id for user in team_1 + team_2]

    update_operations = [
        UpdateOne({"discord_id": member_id}, {"$set": {"last_activity": datetime.datetime.now()}})
        for member_id in team_member_ids
    ]

    await collection.bulk_write(update_operations)```
slate swan
#

why create UpdateOne for each memberid when you can just do UpdateMany

#
await collection.bulk_write([
    UpdateMany(
        {"discord_id": {"$in": team_member_ids}},
        {"$set": {"last_activity": datetime.datetime.now()}}
    )
])
``` something about that
naive briar
young dagger
slate swan
#

!d pymongo.collection.Collection.bulk_write

unkempt canyonBOT
#
bulk_write(requests: Sequence[_WriteOp[_DocumentType]], ordered: bool = True, bypass_document_validation: bool = False, session: ClientSession | None = None, ...) → BulkWriteResult```
Send a batch of write operations to the server.

Requests are passed as a list of write operation instances ( [`InsertOne`](https://pymongo.readthedocs.io/en/stable/api/pymongo/operations.html#pymongo.operations.InsertOne "pymongo.operations.InsertOne"), [`UpdateOne`](https://pymongo.readthedocs.io/en/stable/api/pymongo/operations.html#pymongo.operations.UpdateOne "pymongo.operations.UpdateOne"), [`UpdateMany`](https://pymongo.readthedocs.io/en/stable/api/pymongo/operations.html#pymongo.operations.UpdateMany "pymongo.operations.UpdateMany"), [`ReplaceOne`](https://pymongo.readthedocs.io/en/stable/api/pymongo/operations.html#pymongo.operations.ReplaceOne "pymongo.operations.ReplaceOne"), [`DeleteOne`](https://pymongo.readthedocs.io/en/stable/api/pymongo/operations.html#pymongo.operations.DeleteOne "pymongo.operations.DeleteOne"), or [`DeleteMany`](https://pymongo.readthedocs.io/en/stable/api/pymongo/operations.html#pymongo.operations.DeleteMany "pymongo.operations.DeleteMany")).
young dagger
#

from pymongo import ReturnDocument from motor.motor_asyncio import AsyncIOMotorClient

#

Yeah you are right

slate swan
#

!d pymongo.operations.UpdateMany

unkempt canyonBOT
#
class pymongo.operations.UpdateMany(filter: Mapping[str, Any], update: Mapping[str, Any] | Sequence[Mapping[str, Any]], upsert: bool = False, ...)```
Create an UpdateMany instance.

For use with [`bulk_write()`](https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.bulk_write "pymongo.collection.Collection.bulk_write").
young dagger
young dagger
#

Thanks

odd jasper
slate swan
#

what does doesnt work mean??

odd jasper
#

It does nothing

#

When i execute the cmd

#

Nth happens

slate swan
#

which command

odd jasper
slate swan
#

well actually none of your commands will work cause you did not enable message_content intent

slate swan
slate swan
#

no you just created message_content varriable

#

look how you did it above

odd jasper
#

dumb

#

yea

odd jasper
naive briar
#

Update discord.py

#

Or whatever library you're using

odd jasper
naive briar
#

pip install --update discord.py?

violet cipher
#

I have a problem: No matter wich video I try to play in discord with my music bot, I get the following error: [out#0/s16le @ 0000024d6f171180] Output file does not contain any stream I've already looked it up on the internet but I can't find any working solution.

glad cradle
turbid condor
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

turbid condor
#

!ytdl

unkempt canyonBOT
#
Our youtube-dl, or equivalents, policy

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

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

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

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

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

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

who said they get it from youtube

turbid condor
#

and then deleted

slate swan
#

okay then

left dew
#

i’m wanting to store the inputted values from a modal that can be submitted multiple times so that i can use the inputted information later. but i’m not sure how to store it and how to store the values if the nodal has been answered more than once

alpine oar
#

mind helping me so it doesnt send the welcome message even tho there isnt any errors and yes it is the correct channel
@bot.event
async def on_member_join(member):

channel = member.guild.system_channel

background = Editor("Pic2.jpg")
profile_image = await load_image_async(str(member.avatar.url))

profile = Editor(profile_image).resize((150, 150)).circle_image()
poppins = Font.poppins(size=50, variant="bold")

poppins_small = Font.poppins(size=20, variant="light")

background.paste(profile, (325, 90))
background.ellipse((325, 90), 150, 150, outline="white", stroke_width=5)

background.text((400, 260), f"Welcome to {member.guild.name}", color="white", font=poppins, align="center")
background.text((400, 325), f"{member.name}#{member.discriminator}", color="white", font=poppins_small, align="center")

file = File(fp=background.image_bytes, filename="pic2.jpg")
await channel.send(f"Hello {member.mention}! Welcome to **{member.guild.name} For More Information go to #✗︱rules**")
await channel.send(file=file)
turbid condor
#

Try debugging it and see if it actually works or not

turbid condor
alpine oar
#

!codeblock

unkempt canyonBOT
#
Formatting code on discord

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.

For long code samples, you can use our pastebin.

alpine oar
#
async def on_member_join(member):
 
    channel = member.guild.system_channel

    background = Editor("Pic2.jpg")
    profile_image = await load_image_async(str(member.avatar.url))

    profile = Editor(profile_image).resize((150, 150)).circle_image()
    poppins = Font.poppins(size=50, variant="bold")

    poppins_small = Font.poppins(size=20, variant="light")

    background.paste(profile, (325, 90))
    background.ellipse((325, 90), 150, 150, outline="white", stroke_width=5)

    background.text((400, 260), f"Welcome to {member.guild.name}", color="white", font=poppins, align="center")
    background.text((400, 325), f"{member.name}#{member.discriminator}", color="white", font=poppins_small, align="center")
 
    file = File(fp=background.image_bytes, filename="pic2.jpg")
    await channel.send(f"Hello {member.mention}! Welcome to {member.guild.name} For More Information go to #✗︱rules")
    await channel.send(file=file)```
#

There

naive briar
#

Where syntax highlighting

#

I'm blind without those

alpine oar
#

oh shi wait

naive briar
#

!d discord.Intents.members

unkempt canyonBOT
#

Whether guild member related events are enabled.

This corresponds to the following events...

naive briar
#

Do you have this intent enabled

alpine oar
#

well yea i think i do

turbid condor
#

An intent

slate swan
unkempt canyonBOT
#

discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
slate swan
#

This requires Intents.members to be enabled.

alpine oar
#

so how do i enabel it 💀

slate swan
#

like every other intent

#

show how you defined your intents

alpine oar
#

but it worked fine when i first coded it

copper gulch
#

how do I do the

ctx.guild.region

its not working for me like it has been changed, it works last time I opened the bot

turbid condor
alpine oar
#

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

slate swan
unkempt canyonBOT
#

The preferred locale for the guild. Used when filtering Server Discovery results to a specific language.

Changed in version 2.0: This field is now an enum instead of a str.

alpine oar
copper gulch
#

ok ok thanks

turbid condor
#

Welp that's what you get for copying a code from yt

alpine oar
turbid condor
#

I'm 100% percent you did

alpine oar
#

well i am 100% i didnt

turbid condor
#

Welp that aside

slate swan
alpine oar
turbid condor
#

Try restarting your bot and see if it works

slate swan
#

like see if it even runs

alpine oar
slate swan
#

for example .system_channel is optional i belive

alpine oar
#

but my godbye msg works perfectly fine

slate swan
#

!d discord.Guild.system_channel

unkempt canyonBOT
#

property system_channel```
Returns the guild’s channel used for system messages.

If no channel is set, then this returns `None`.
turbid condor
slate swan
#

you have any other on_member_join event defined else in your code?

alpine oar
naive briar
#

(or an error handler eating up the errors)

turbid condor
turbid condor
#

Zzz

slate swan
#

use @bot.listen() instead

alpine oar
#

i forgot i had this @bot.event async def on_member_join(member): guild = member.guild role = discord.utils.get(guild.roles, name='👑 Pirates 👑') if role is not None: await member.add_roles(role)

alpine oar
#

alr thanks

turbid condor
slate swan
# alpine oar oh

also using @bot.listen() you can pass event name into decorator and name function other name

#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").

Example...
slate swan
#

just pass name

#

did you check if this method is called?

alpine oar
#

so i did the @bot.listen() on like every line i had the @bot.event() on

slate swan
#

if you meant @bot.event (without the ()) then should be good

alpine oar
#

finally i am good

slate swan
#

put a print statement inside

alpine oar
slate swan
naive briar
#

What even is asyncio.async

turbid condor
#

I think i asked him to debug

slate swan
turbid condor
#

Welp do what down told u to

#

And see if it's even printing

slate swan
#

i belive by debugging he wanted you to put some print statements inside and see which varriable holds what so you can get more in depth what is going on

sullen shoal
slate swan
#

so most possible case: you did not load the cog

slate swan
turbid condor
#

Btw no need to process commands in a listener

alpine oar
#

well i did make it work so i am done with that ima move on code smt else

turbid condor
#

It's a listener not an event

naive briar
#

What do you mean load the event

turbid condor
#

Listener already handles the process command for you

#

In your cog put this

async def on_cog_load(self):
    print('loaded')```
#

Inside the listener

naive briar
#

Inside the listener??

sullen shoal
#

as a listener

turbid condor
#

Wrong ping

#

Just make sure it's aligned with your async def on_message

naive briar
#

Who isn't

sullen shoal
#

@slate swanwhat's your issue

turbid condor
#

His listener isn't firing

#
    
@commands.Cog.listener()
async def on_message(self, message: discord.Message) -> None:
        print("test")
        if message.author != self.bot.user or not message.author.bot and message.mentions and message.type != discord.MessageType.reply:
            async with self.bot.pool.acquire() as conn:
                async with conn.cursor(aiomysql.DictCursor) as cursor:
                    for mention in message.mentions:
                        await cursor.execute("SELECT emojitag, emojiID FROM auto_react WHERE guildID=%s AND targetID=%s;", (message.guild.id, mention.id))
                        fetch: tuple[dict] | None = await cursor.fetchall()
                        for emoji in fetch:
                            await message.add_reaction("<:{}:{}>".format(emoji["emojitag"], emoji["emojiID"]))
        
async def on_cog_load():
    print('loaded')
sullen shoal
#

if message.author != self.bot.user or not message.author.bot and message.mentions and message.type != discord.MessageType.reply: what is your intention with this conditional statement

turbid condor
#

Not even loaded?

naive briar
#

Is it even a valid listener/event

turbid condor
#

Nvm i forgot to put self

naive briar
#

!d discord.ext.commands.Cog.cog_load

unkempt canyonBOT
#

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

A special method that is called when the cog gets loaded.

Subclasses must replace this if they want special asynchronous loading behaviour. Note that the `__init__` special method does not allow asynchronous code to run inside it, thus this is helpful for setting up code that needs to be asynchronous.

New in version 2.0.
turbid condor
#

Mb it was cog_load not on_cog_load

copper gulch
#
@client.command(aliases=['user', 'userinfo'])
async def info(ctx, user: discord.Member):
    """Gets info on a member, such as their ID."""
    embed = discord.Embed(title="User profile: " + user.name, colour=user.colour)
    embed.set_image(url = user.banner)
    embed.add_field(name="Name:", value=user.name)
    embed.add_field(name="ID:", value=user.id)
    embed.add_field(name="Status:", value=user.status)
    embed.add_field(name="Highest role:", value=user.top_role)
    embed.add_field(name="Joined:", value=user.joined_at)
    embed.set_thumbnail(url=user.avatar)
    await ctx.send(embed=embed)

ok I need help, its not showing the user's banner, aswell as how to do the new Client.fetch_user thing

turbid condor
#

Nah it's cog_load i just checked my github repo and docs

copper gulch
#

ok ok

copper gulch
sullen shoal
# unkempt canyon

actually, you're correct. This is not an event, so it does not need to be declared an event.

slate swan
#

Banner is an asset

#

!d discord.Asset

unkempt canyonBOT
#

class discord.Asset```
Represents a CDN asset on Discord.

str(x) Returns the URL of the CDN asset.

len(x) Returns the length of the CDN asset’s URL.

x == y Checks if the asset is equal to another asset.

x != y Checks if the asset is not equal to another asset.

hash(x) Returns the hash of the asset.
slate swan
#

Check what attributes it has

copper gulch
#

hmmm

slate swan
#

Also banner is optional it could be that user Has no banner

#

You need to check if it exists

copper gulch
#

because the set_image for an embed requires URL

slate swan
copper gulch
#

Ill try asset.url etc...

ember mango
#

@slate swan
You use discord or disnake?

slate swan
naive briar
#

No one use Discord

ember mango
#

I used disnake

slate swan
#

Cool Like

ember mango
#

Because Disnake Very easy

turbid condor
#

Welp I'd get some sleep I'm messing up too much now

copper gulch
#

ok Im so confused, how do I put the banner image/gif into the embed

#

someone spoonfeed me xd

ember mango
#

When you learn it, you get addicted. Programming is like that

copper gulch
#

Im so lost

left dew
ember mango
copper gulch
ember mango
copper gulch
#

thx :D

#

Im so outdated with this version, I havent touched my code since last year

turbid condor
#

!rule 10

unkempt canyonBOT
#

10. Do not copy and paste answers from ChatGPT or similar AI tools.

ember mango
naive briar
#

Lmao

ember mango
copper gulch
#

so what I learned so far is banner is an asset

#

and that it requires await fetch user?

ember mango
#

BRUHHH

naive briar
#

!d discord.Member.banner

turbid condor
#

Yeah it will be none if the user doesn't have a banner

naive briar
#

!d discord.User.banner

unkempt canyonBOT
#

property banner```
Returns the user’s banner asset, if available.

New in version 2.0.

Note

This information is only available via [`Client.fetch_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.fetch_user "discord.Client.fetch_user").
naive briar
#

Right

copper gulch
ember mango
copper gulch
#

maybe its because the user is using a GIF?

naive briar
#

You need to fetch the user/member to access their banners

turbid condor
#

Nope shouldn't be a problem

ember mango
left dew
#

does anyone know how i would input the data that has been inputted into a modal into a database but the modal has been answered multiple times?

ember mango
#

Not ChatGBT

ember mango
naive briar
#

It's still correct, so it's probably fine

ember mango
#

I helped him

naive briar
#

You spoonfed them

naive briar
#

Which you shouldn't

copper gulch
#
In user_id: Value "n3srei" is not snowflake.

anyone know how to fix this kind of error?

#

what is a snowflake

#
@client.command(aliases=['user', 'userinfo'])
async def info(ctx, user: discord.Member):
    Userdiscord = await client.fetch_user(user)
    """Gets info on a member, such as their ID."""
    embed = discord.Embed(title="User profile: " + user.name, colour=user.colour)
    embed.set_image(url = Userdiscord.banner)
    embed.add_field(name="Name:", value=user.name)
    embed.add_field(name="ID:", value=user.id)
    embed.add_field(name="Status:", value=user.status)
    embed.add_field(name="Highest role:", value=user.top_role)
    embed.add_field(name="Joined:", value=user.joined_at)
    embed.set_thumbnail(url=user.avatar)
    await ctx.send(embed=embed)
turbid condor
left dew
slate swan
copper gulch
upbeat ice
#

theres no such thing as spoonfeeding here...

#

This is a help server

naive briar
#

Is it?

turbid condor
# left dew wdym?

Like instead of the user_id as a key value use an index to make enteries

turbid condor
#

Where else are you storing the submissions?

left dew
#

nowhere

#

i’m just really confused as to how i’d store the data if the modal has been answered more than once by the same user

turbid condor
upbeat ice
#

overwrite or append the db

slate swan
left dew
upbeat ice
#

what db are you using?

left dew
#

mysql

slate swan
#

Hi

left dew
#

do i do cursor.execute(sql, data)?

upbeat ice
#

you can use an update statement

left dew
#

sql is the INSERT etc etc

copper gulch
#

difference of Author and User?

#

in this version?