#discord-bots

1 messages ยท Page 294 of 1

slate swift
#

show code?

lethal drift
#

Here's the check part of it

 def check(msg):
        if isinstance(context, discord.Interaction):
            print(context.message.id, msg.id)
            if context.message.id != msg.id:
                return True
        if context.message.id != msg.id:
            return True

The second part works, (the part that handles regular commands) but the slash command version isn't working because a message doesn't exist at the time of the purge

golden portal
#

could just use before kwargs of channel.purge and then use interaction.id, it would fetch messages before the interaction command

toxic moat
#

@naive briar still doesnt work ballsad

quick brook
#

you should ask this on the dpy server tbh

#

idk if down or the others know about it

naive briar
#

Yeah, why do we even have this channel if discord.py server exist

wispy pasture
#
class CreateSelect(discord.ui.View):

    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.select(
        custom_id="guide",
        options=[
            discord.SelectOption(label = 'What is Sampler', emoji = 'U+2728'),
            discord.SelectOption(label = 'Guide to AI Models', emoji = 'U+1F4DA'),
        ],
    )```


uhhh?
lethal drift
quick brook
buoyant quail
lethal drift
quick brook
wispy pasture
wispy pasture
quick brook
#

like the ones from ?charinfo

wispy pasture
naive briar
#

!charinfo ๐Ÿ˜บ

unkempt canyonBOT
wispy pasture
quick brook
#

\U0001f4da - books
\U00002728 - sparkles

#

also need to construct an discord.PartialEmoji() for those

toxic moat
wispy pasture
#

why does it not wonna work like my other code ๐Ÿ˜ญ

buoyant quail
wispy pasture
quick brook
#

so basically what this means is that within your emoji kwarg (for example the first one), it will be emoji=discord.PartialEmoji(name=\U00002728)

naive briar
golden portal
toxic moat
wispy pasture
golden portal
#

!d discord.SelectOption

unkempt canyonBOT
#

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

These can be created by users.

New in version 2.0.
quick brook
naive briar
#

I think it's just a faulty linter

#

!e

print("\U0001f63a")
unkempt canyonBOT
#

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

๐Ÿ˜บ
quick brook
#

gonna have to whip out jsk

toxic moat
#

can someone help me or no

quick brook
#

you are going to have to explain what are you trying to do

toxic moat
quick brook
#

it should log it if you have logging set up

naive briar
naive briar
toxic moat
#
from discord.ext import commands, tasks
import asyncio

intents = discord.Intents.default()
intents.message_content = True
intents.messages = True
intents.members = True

# Initialize bot with command prefix '!'
bot = commands.Bot(command_prefix='!', intents=intents)

BOT_PREFIX = '!'

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name} - {bot.user.id}')
    print('------')
    watching_activity = discord.Activity(type=discord.ActivityType.watching, name="over AutoShop")
    await bot.change_presence(activity=watching_activity)

@bot.command()
async def purchase(ctx):
    # Replace these placeholders with your actual PayPal and crypto wallet addresses
    paypal_address = "**[PayPal](https://www.paypal.me/erfanproguy2)**"
    bitcoin_wallet = '**bc1q5cf7v6lr7yrtdferlqq07hqww7wqw8dfwp5a66**'
    litecoin_wallet = '**Laf9AR7LdtrpkrTgFkx5RVci65ngxViTqa**'
    ethereum_wallet = '**0x3f74a98bA3468e25F9cFc02852BF7883B4D707e9**'

    embed = discord.Embed(title="Purchase Information", description="Here are the following purchase options:", color=0x00ff00)
    embed.add_field(name="![paypal](https://cdn.discordapp.com/emojis/1145503563934609529.webp?size=128 "paypal") Paypal", value=paypal_address, inline=False)
    embed.add_field(name="![btc](https://cdn.discordapp.com/emojis/1145502468957032598.webp?size=128 "btc") Bitcoin Wallet", value=bitcoin_wallet, inline=False)
    embed.add_field(name="![ltc](https://cdn.discordapp.com/emojis/1145502474879381586.webp?size=128 "ltc") Litecoin Wallet", value=litecoin_wallet, inline=False)
    embed.add_field(name="![eth](https://cdn.discordapp.com/emojis/1145502472882892920.webp?size=128 "eth") Ethereum Wallet", value=ethereum_wallet, inline=False)
    await ctx.send(embed=embed)

@bot.event
async def on_message(message):
    if bot.user.mentioned_in(message):
        # Respond with the bot's prefix
        await message.channel.send(f"My prefix is `{BOT_PREFIX}`")

bot.run('')```

it was working earlier even when i didnt process ;-;
quick brook
#

sounds like a scam bot

naive briar
quick brook
#

just shut it down at this rate

toxic moat
naive briar
quick brook
finite sage
toxic moat
golden portal
naive briar
quick brook
quick brook
naive briar
#

Yes?

quick brook
#

nonetheless, just set the command_prefix to have the command.when_mention func to process mentions

naive briar
#

They are apparently want to tell the prefix to the user when they mentioned the bot

quick brook
#

you guys can't understand what the on_message code even does with op

naive briar
#

What do you mean?

quick brook
#

anyways, op never even mentioned the error

naive briar
#

There are no errors, only that the bot doesn't process the commands

toxic moat
#

oh my processing was still in my if statement

#

works now ๐Ÿ‘

#

thank you catlover

#

and noelle

quick brook
#

ok

lethal drift
formal basin
#

!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...
tepid dagger
#

how do you send a path thingy to a channel, eg #discord-bots through the bot

naive briar
#

!d discord.TextChannel.mention

unkempt canyonBOT
tepid dagger
#

howโ€™d you send it

naive briar
#

๐Ÿคท

await ctx.send(content=channel.mention)
tepid dagger
#

ok

#

and youโ€™d define channel as like

client.get_channel(id)?
quick brook
quick brook
#

The isinstance check is to make sure pyright doesn't throw errors

harsh orbit
#

How I can get role name by ID?

meager chasm
unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID.

Changed in version 2.0: `role_id` parameter is now positional-only.
toxic moat
#
@commands.has_permissions(ban_members=True)
async def unban(ctx, *, member_id):
    try:
        banned_users = await ctx.guild.bans()
        member_id = int(member_id)
        banned_user = discord.utils.find(lambda ban: ban.user.id == member_id, banned_users)
        
        if banned_user:
            await ctx.guild.unban(banned_user.user)
            
            embed = discord.Embed(
                title="User Unbanned",
                description=f"User ID {member_id} has been unbanned by {ctx.author.mention}.",
                color=discord.Color.green()
            )
            await ctx.send(embed=embed)
        else:
            embed = discord.Embed(
                title="Unban Error",
                description=f"User ID {member_id} is not currently banned.",
                color=discord.Color.red()
            )
            await ctx.send(embed=embed)
    except ValueError:
        embed = discord.Embed(
            title="Unban Error",
            description="Invalid member ID provided.",
            color=discord.Color.red()
        )
        await ctx.send(embed=embed)
    except discord.Forbidden:
        embed = discord.Embed(
            title="Unban Error",
            description="I don't have the necessary permissions to unban members.",
            color=discord.Color.red()
        )
        await ctx.send(embed=embed)

Why doesnt this unban command work?

golden portal
toxic moat
wispy pasture
#

my code:

@bot.hybrid_command(name="imagine-guide")
async def ticket(ctx):
    embed = discord.Embed(title = "> Guide to AI Models", color = 0x714fff)
    embed.set_author(name = "Guide to Using the Image Generation System:")
    embed.description = "To make it easier to use the image generation system, we've created a handy guide to help you get started with this. This comprehensive guide provides detailed information about each AI Model and Sampler used in the Imagine system to give you a clear understanding of everything."
    await ctx.send(embed, view=CreateSelect())```

and the output which comes:
golden portal
slate swan
#

!d discord.ext.commands.Context.send

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

Sends a message to the destination with the content given.

This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for non-interaction contexts.

For interaction based contexts this does one of the following...
slate swan
wispy pasture
#

ohhhhhh

wispy pasture
toxic moat
golden portal
toxic moat
# golden portal just in your command function, anywhere at the top
@commands.has_permissions(ban_members=True)
async def unban(ctx, *, member_id):
    try:
        banned_users = await ctx.guild.bans()
        member_id = int(member_id)
        banned_user = None
        print("Command loaded")

        for ban_entry in banned_users:
            user = ban_entry.user
            if user.id == member_id:
                banned_user = user
                break

        if banned_user:
            await ctx.guild.unban(banned_user)

            embed = discord.Embed(
                title="User Unbanned",
                description=f"User ID {member_id} has been unbanned by {ctx.author.mention}.",
                color=discord.Color.green()
            )
            await ctx.send(embed=embed)
        else:
            embed = discord.Embed(
                title="Unban Error",
                description=f"User ID {member_id} is not currently banned.",
                color=discord.Color.red()
            )
            await ctx.send(embed=embed)
    except ValueError:
        embed = discord.Embed(
            title="Unban Error",
            description="Invalid member ID provided.",
            color=discord.Color.red()
        )
        await ctx.send(embed=embed)
    except discord.Forbidden:
        embed = discord.Embed(
            title="Unban Error",
            description="I don't have the necessary permissions to unban members.",
            color=discord.Color.red()
        )
        await ctx.send(embed=embed)```

never printed
golden portal
#

do you have message content intents enabled?

golden portal
#

do you have an error handler?

toxic moat
#

error handler works

golden portal
#

show it

toxic moat
# golden portal show it
async def ban_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        embed = discord.Embed(
            title="Missing Argument",
            description="Please specify the user to ban.",
            color=discord.Color.red()
        )
        await ctx.send(embed=embed)
    elif isinstance(error, commands.BadArgument):
        embed = discord.Embed(
            title="User Not Found",
            description="The specified user was not found.",
            color=discord.Color.red()
        )
        await ctx.send(embed=embed)
    elif isinstance(error, commands.CheckFailure):
        embed = discord.Embed(
            title="Permission Error",
            description="You don't have permission to use this command.",
            color=discord.Color.red()
        )
        await ctx.send(embed=embed)```
golden portal
slate swan
#

raise error would work wouldnt it

golden portal
#

it would

slate swan
golden portal
#

lmao they showed the wrong error handler

toxic moat
#

oh shoot

#

i have 2 because i was testing

slate swan
#

but they have to do that for each anyways

toxic moat
#

oh wait yeah

golden portal
#

could've just let the global error handler see it

golden portal
toxic moat
slate swan
#

you need to send it in the if body

toxic moat
slate swan
#

!e ```py
if False:
a = 10
else:
print(a)

unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 4, in <module>
003 |     print(a)
004 |           ^
005 | NameError: name 'a' is not defined
slate swan
toxic moat
slate swan
#

should be good with this one

#

i would just change it to raise error instead

golden portal
#

it's a chained error anyways so

slate swan
#

now you need to apply this logic to each error handler you have

#

!e ```py
def div():
return 1 / 0

def handle(err):
raise

try:
div()
except Exception as e:
handle(e)

unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 10, in <module>
003 |     handle(e)
004 |   File "/home/main.py", line 8, in <module>
005 |     div()
006 |   File "/home/main.py", line 2, in div
007 |     return 1 / 0
008 |            ~~^~~
009 | ZeroDivisionError: division by zero
slate swan
#

yep

golden portal
toxic moat
#

TypeError: object async_generator can't be used in 'await' expression

toxic moat
slate swan
unkempt canyonBOT
#

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

You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#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
#

its async for ... in bans(...)

#

not await bans(...)

toxic moat
slate swan
fading linden
# unkempt canyon

it changed from a list to an async iterator because of a breaking change..

pure hatch
#

Hello,
Have any good tutorial how to make a different folder like "commands" and my main.py identify this folder and register the commands?

I'm having alot of problems like
discord.ext.commands.errors.CommandNotFound: Command "addpergunta" is not found

buoyant quail
#

Interesting that they didn't even put load_extension there.
Ah, they did

wispy pasture
#

it says invalid syntax....

slate swan
#

yeah decorator is supposed to be above a function

#

you cant put code in between them

wispy pasture
#

oh...

vocal snow
#

id really recommend understanding how decorators work because of how extensively used they are in discord.py

wispy pasture
vocal snow
#

?

#

decorators aren't a particularly difficult thing to understand

unkempt canyonBOT
#
Decorators

A decorator is a function that modifies another function.

Consider the following example of a timer decorator:

>>> import time
>>> def timer(f):
...     def inner(*args, **kwargs):
...         start = time.time()
...         result = f(*args, **kwargs)
...         print('Time elapsed:', time.time() - start)
...         return result
...     return inner
...
>>> @timer
... def slow(delay=1):
...     time.sleep(delay)
...     return 'Finished!'
...
>>> print(slow())
Time elapsed: 1.0011568069458008
Finished!
>>> print(slow(3))
Time elapsed: 3.000307321548462
Finished!

More information:
โ€ข Corey Schafer's video on decorators
โ€ข Real python article

minor spire
#

Heyo ppl, I'm looking for some assistance in getting this damn bot to send alerts

#

@slate swan me? Intents are set

slate swan
#

showing your code would be helpful

buoyant quail
#

Show your code and explain what's going wrong
We are not magicians ๐Ÿคทโ€โ™‚๏ธ

slate swan
#

โ€ข Ask your Python question, not if you can ask or if there's an expert who can help.
โ€ข Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
โ€ข Explain what you expect to happen and what actually happens.

minor spire
#

Surely would, but I'm on the toilet lol

#

One moment @buoyant quail

buoyant quail
#

Did you set it in the code?

slate swan
#

you need to enable it in code too

#

!mcintent

unkempt canyonBOT
#
Discord Message Content Intent

The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."

The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.

Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:

intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents

bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor

For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.

minor spire
#

@buoyant quail here ya go

#

???

buoyant quail
minor spire
#

too flippin long

buoyant quail
#

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

minor spire
#

still learning here ๐Ÿ˜ฆ

buoyant quail
#

default intents does not include message_content

minor spire
#

well i don't need a users message

vocal snow
minor spire
#

its not meant to be interactive, simply fetch data from the api and send the alert @vocal snow

buoyant quail
#

You have a command start_alerts
How you want it to be triggered, if you can't access the messages?

minor spire
#

holy shit

vocal snow
#

so the start_alerts command is not meant to be used

minor spire
#

im gonna go hide in the corner now

vocal snow
#

happens to the best of us

minor spire
#

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

slate swan
vocal snow
#

you want message_content

slate swan
#

!mcintent

unkempt canyonBOT
#
Discord Message Content Intent

The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."

The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.

Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:

intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents

bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor

For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.

minor spire
#

@bot.command()
async def start_alerts(ctx):
await ctx.send(f"Alerts started with message: {message_content}")

#

better?

slate swan
#

and from where you get the message_content varriable here?

minor spire
#

ah! i do not

#

@slate swan @vocal snow @buoyant quail any better?

buoyant quail
#

nope

minor spire
#

wtf

buoyant quail
#

also you did show your token

minor spire
#

awesome

buoyant quail
#

and the message_content is not enabled still

buoyant quail
frozen pivot
#

intents.overnight_billionare = True

minor spire
#

welp that was a quick server kill

exotic island
naive briar
#

Why is that?

sick birch
#

It means you can't have capital letters

exotic island
#

I making transcript and i have a question
How i sand smth like message auhtor name: 'text'

#

now i have smth like this

#

i need
msg auhtor name : 1

ember mango
#

Can you create something in python that takes people's tokens

#

python can?

radiant shuttle
#
import discord
TOKEN = "TOKEN"
client = discord.Client()
@client.event
async def on_ready():
    print("RUNNING")
@client.event
async def on_message(message):
    channel = client.get_channel(818202447067480084)
    if message.channel.id == channel.id:
        if (message.author.bot) or (message.content) == '-clear':
            return
        embed = embed_for_user(message.author)
        if'\n'in message.content:embed.add_field(name=message.content.split('\n')[0],value=''.join(message.content.split('\n')[1:]))
        else:embed.description=message.content
        embed.color = 0xdd4c59
        embed.timestamp = __import__('datetime').datetime.utcnow() # UTC better
        embed.set_footer(text="Instagram", icon_url="https://images-ext-1.discordapp.net/external/4386b73r8DPwBkrBH6gPpeIFvxsg-yZjz3DFXSq-cLg/https/images-ext-2.discordapp.net/external/C6jCIKlXguRhfmSp6USkbWsS11fnsbBgMXiclR2R4ps/https/www.instagram.com/static/images/ico/favicon-192.png/68d99ba29cc8.png")
        send_extras = {}
        if message.attachments:
            file = await message.attachments[0].to_file()
            file.filename = file.filename.replace("_", "")
            embed.set_image(url=f"attachment://{file.filename}")
            send_extras['file'] = file
        await channel.send(embed=embed, **send_extras)
        await message.delete()
def embed_for_user(user):
    embed = discord.Embed()
    embed.set_author(name=f"{user.name}", icon_url= user.avatar_url)
    return embed
client.run(TOKEN)
print(client.user.name)
#
D:\pythonProject\Scripts\python.exe C:/Users/pirat/PycharmProjects/pythonProject/main.py
Traceback (most recent call last):
  File "C:/Users/pirat/PycharmProjects/pythonProject/main.py", line 3, in <module>
    client = discord.Client()
TypeError: __init__() missing 1 required keyword-only argument: 'intents'

Process finished with exit code 1

slate swan
#

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

radiant shuttle
#

where is the error

slate swan
#

client = discord.Client()
TypeError: init() missing 1 required keyword-only argument: 'intents'

slate swan
radiant shuttle
#

yes what do i habe to do

#

have

slate swan
#

create Intents instance and pass it to Client

radiant shuttle
#

it was working last year is is a copy paste past code

radiant shuttle
slate swan
slate swan
#

just instead of commands.Bot you have discord.Client

ember mango
#

Why not work?

#
import time
import random
payload = {
    'content': (['Hi','by'])
}```
@slate swan ![pithink](https://cdn.discordapp.com/emojis/652247559909277706.webp?size=128 "pithink")
radiant shuttle
# slate swan everything is explained here https://discord.com/channels/267624335836053506/343...
import discord
from discord import Intents

TOKEN = "token"
intents = Intents.default()
intents.message_content = True
client = discord.Client(command_prefix="!", intents=intents)
@client.event
async def on_ready():
    print("RUNNING")
@client.event
async def on_message(message):
    channel = client.get_channel(1145730366963990619)
    if message.channel.id == channel.id:
        if (message.author.bot) or (message.content) == '-clear':
            return
        embed = embed_for_user(message.author)
        if'\n'in message.content:embed.add_field(name=message.content.split('\n')[0],value=''.join(message.content.split('\n')[1:]))
        else:embed.description=message.content
        embed.color = 0xdd4c59
        embed.timestamp = __import__('datetime').datetime.utcnow() # UTC better
        embed.set_footer(text="Instagram", icon_url="https://images-ext-1.discordapp.net/external/4386b73r8DPwBkrBH6gPpeIFvxsg-yZjz3DFXSq-cLg/https/images-ext-2.discordapp.net/external/C6jCIKlXguRhfmSp6USkbWsS11fnsbBgMXiclR2R4ps/https/www.instagram.com/static/images/ico/favicon-192.png/68d99ba29cc8.png")
        send_extras = {}
        if message.attachments:
            file = await message.attachments[0].to_file()
            file.filename = file.filename.replace("_", "")
            embed.set_image(url=f"attachment://{file.filename}")
            send_extras['file'] = file
        await channel.send(embed=embed, **send_extras)
        await message.delete()
def embed_for_user(user):
    embed = discord.Embed()
    embed.set_author(name=f"{user.name}", icon_url= user.avatar_url)
    return embed
client.run(TOKEN)
print(client.user.name)
#
[2023-08-28 17:46:59] [ERROR   ] discord.client: Ignoring exception in on_message
Traceback (most recent call last):
  File "D:\pythonProject\lib\site-packages\discord\client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "C:/Users/pirat/PycharmProjects/pythonProject/main.py", line 17, in on_message
    embed = embed_for_user(message.author)
  File "C:/Users/pirat/PycharmProjects/pythonProject/main.py", line 33, in embed_for_user
    embed.set_author(name=f"{user.name}", icon_url= user.avatar_url)
AttributeError: 'Member' object has no attribute 'avatar_url'
ember mango
#

anyone can help me?????////

radiant shuttle
#

now whats the problem

slate swan
ember mango
slate swan
slate swan
#

!e ```py
import random

payload = {
'content': (['Hi','by'])
}

random.choice(payload)

unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 8, in <module>
003 |     random.choice(payload)
004 |   File "/usr/local/lib/python3.11/random.py", line 374, in choice
005 |     return seq[self._randbelow(len(seq))]
006 |            ~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^
007 | KeyError: 0
slate swan
#

random.choice takes list not dictionary

#

then you did something wrong

#

!e ```py
import random
x = [1, 2 ,3 , 4, 5]
print(random.choice(x))

unkempt canyonBOT
#

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

2
#
Missing required argument

code

buoyant quail
slate swan
#

payload is a dict

radiant shuttle
slate swan
#
  1. full traceback
  2. It tells you what's wrong
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.

sick birch
#

Don't ask for help with such things here please

radiant shuttle
#

how can i start a code getting source from html site( its my first time trying to white pythong with html)

radiant shuttle
final iron
#

!d aiohttp

unkempt canyonBOT
#

Common data structures used by aiohttp internally...

quick brook
#

Honestly we need to get R. Danny in here for the tags

#

Promoting Dannyware

quick brook
#

Good example of this

shadow rose
#

What could be the reason that my bot doesn't respond to commands?

quick brook
shadow rose
shadow rose
#
import os
import random

import requests

import discord
from discord.ext import commands
from dotenv import load_dotenv

load_dotenv()

TOKEN = os.getenv("DISCORD_BOT_TOKEN")
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='/', intents=intents)
bot.remove_command('help')

API_response = requests.get("https://api.earthmc.net/v2/aurora/towns/Atlanta/").json()

print(API_response)


@bot.command()
async def help(ctx):
    embed = discord.Embed(
        title='Help section',
        description='Welcome to the help section',
        colour=discord.Colour.brand_green()
    )

    await ctx.send(embed=embed)


@bot.event
async def on_ready():
    messages = [f'Logged in as {bot.user.name}', f'{bot.user.name} is ready to work', f'{bot.user.name} is alive', f'{bot.user.name} is ready to help']
    await bot.get_channel(1145525565043003462).send(random.choice(messages))


@bot.event
async def on_message(message):
    # Check if the message is not from the bot
    if message.author.bot:
        return

    user_message = message.content.lower()
    response = ''

    if user_message[0] == '/':
        return

    if user_message in ['hey', 'hello', 'hi']:
        response = f'Hello, {message.author}'

    await message.channel.send(response)


def run_discord_bot():
    bot.run(TOKEN)
quick brook
shadow rose
#

no, it's my first time coding a discord bot

quick brook
# shadow rose no, it's my first time coding a discord bot
class MyHelpCommand(commands.MinimalHelpCommand):
    def get_command_signature(self, command):
        return '{0.clean_prefix}{1.qualified_name} {1.signature}'.format(self, command)

class MyCog(commands.Cog):
    def __init__(self, bot):
        self._original_help_command = bot.help_command
        bot.help_command = MyHelpCommand()
        bot.help_command.cog = self

    def cog_unload(self):
        self.bot.help_command = self._original_help_command```
See the documentation: <https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#help-commands> for more details.
For migrating from old helpformatters: <https://discordpy.readthedocs.io/en/latest/migrating.html#helpformatter-and-help-command-changes>

A walkthrough on subclassing help: 
<https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96>
shadow rose
#

thx

quick brook
#

np

#

The reason why your bot is not listening for the help command is that you pretty much effectively removed it

shadow rose
#

oh, okay

quick brook
#

And do not use requests

#

Use aiohttp, which is non-blocking

rustic edge
rustic edge
#

Ty

quick brook
#

By using something like requests, you essentially block your whole entire bot event loop

rustic edge
#

Ohhh

#

Cause itโ€™s not async

#

Right

quick brook
#

Which renders your whole entire bot useless while processing the http requests (w/ requests)

rustic edge
#

So itโ€™s a different loop

quick brook
rustic edge
#

Gotcha

quick brook
rustic edge
#

Ok.

#

Tysm again

quick brook
shadow rose
#

so, it should make it much faster if I can request multiple API's at the same time with aiohttp?

quick brook
buoyant quail
shadow rose
buoyant quail
#

What happen?

shadow rose
#

nvm, I'll just read the documentation

#

it was about the on_message

slate swan
#

Hey guys,

In need of some assistance if anyone can answer.

I have some code thatโ€™s throwing a recursion error however itโ€™s only when I run it on this on pc. When I run it on any other computer it runs perfectly fine so I don't believe its a code issue as it should hypothetically be doing the same thing on my other pc. However on my other computer the code runs and does as its supposed to no problem.

I've searched the history of recursion error in this guild but wasn't able to find anyone with a similar problem and most of google says it has to do with the code. But again works fine on another pc

Last night I uninstalled python and it fixed it for like 35 minutes. Then started spamming the error in the console. But I've had said code running for 5+ hours on other pc with no issues

buoyant quail
slate swan
#

It is in a discord bot.

Unfortuantely its 3k+ lines ( has a bunch of functions and requests being made ) and it doesn't specify where the error is from. I have added some debug prints but they aren't showing much either

buoyant quail
#

We can't guess what's going by you without any code and errors

#

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

slate swan
#

thanks. Ill continue browsing and see as the issue isn't the code but more of a computer thing so maybe your right and I should bring it to #1035199133436354600

vocal snow
#

doesn't specify where the error is

#

do you have an error handler?

#

Are you printing exception objects?

vale wing
#

Please show traceback

slate swan
vale wing
#

You cannot guarantee it's device-dependent, I suspect it's random

vale wing
slate swan
slate swan
vale wing
#

I remember one guy being absolutely sure that adding a print() into his code that does API requests fixes error caused by something above that print

#

Your case might be similar to this

slate swan
#

hmm

slate swan
# vale wing So can you show traceback?

Ran it again and got

Maximum recursion depth exceeded while calling a python object | Function: GetProxy

GetProxy code:

def getproxy():
    try:
        with open("Data/proxies.txt", "r") as file:
            proxies = file.read().splitlines()
        proxy = random.choice(proxies)
        return {'http': f'http://{proxy}', 'https': f'http://{proxy}'}
    except Exception as e:
        print(f"{str(e).capitalize()} | Function: GetProxy, Retrying", False)
        pass
slate swan
#

oh dammit it didn't copy

vale wing
#

Raise the exception instead of printing it

#

And not full code definitely since you don't call the function from itself hence there's no recursion

buoyant quail
#

And the output from here would be
Maximum recursion depth exceeded while calling a python object | Function: GetProxy, Retrying False
not just
Maximum recursion depth exceeded while calling a python object | Function: GetProxy

vale wing
#

Indeed

#

Most likely many functions and other stuff named getproxy causing confusion

#

That's why shouldn't have everything in one file

slate swan
#

!e ```py
def x():
x()

x()```

unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 4, in <module>
003 |     x()
004 |   File "/home/main.py", line 2, in x
005 |     x()
006 |   File "/home/main.py", line 2, in x
007 |     x()
008 |   File "/home/main.py", line 2, in x
009 |     x()
010 |   [Previous line repeated 996 more times]
011 | RecursionError: maximum recursion depth exceeded
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/NK7TEF7T4H6IAEPKXJXGCRPWH4

final iron
carmine pilot
#

Error: Name "Get" is not defined

final iron
#

Pretty clear error

#

Get isn't anything

carmine pilot
#

r u fr?

#

what do i put then??

final iron
#

No, the error is lying to you

#

Well Get isn't in your code

#

Share the full traceback

#

Did you import get from discord.utils?

carmine pilot
#

no..

final iron
#

Okay, so how would this work then

#

Pretty obvious what you need to do

carmine pilot
#

ill see if it worked

slate swan
#

yea functions dont spawn randomly you need to import them

carmine pilot
#

mb

final iron
slate swan
final iron
#

Can't say without getting muted

carmine pilot
#

it seems that when i put whatevery i need to put in my status it applies my role but when I remove it it doesnt remove like its supposed to

carmine pilot
#

look up

vale wing
#

Isn't presence update a different event or it was changed

#

!d discord.on_presence_update

unkempt canyonBOT
#

discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) updates their presence.

This is called when one or more of the following things change:

โ€ข status

โ€ข activity

This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences) and [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be enabled...
final iron
#

!d discord.on_member_update

unkempt canyonBOT
#

discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) updates their profile.

This is called when one or more of the following things change...
vale wing
final iron
#

Yup

#

Not sure why he's using it

vale wing
#

@carmine pilot you're listening to wrong event

carmine pilot
#

so nothing i can do now?

final iron
#

What

#

Just change the event

vale wing
#

Just change on_member_update to on_presence_update

subtle spade
#

Hi, I cant get this simple thing to work. Is something wrong with this lines? The bot will not answer

async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!test'):
await message.channel.send('Ok!')

final iron
carmine pilot
final iron
subtle spade
final iron
subtle spade
final iron
#

...

carmine pilot
formal basin
#

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

quick brook
#

Hi does someone want to review my cog?
https://github.com/No767/Kumiko/blob/dev/Bot/Cogs/config.py
Here are some background knowledge that you are going to need:

  • Redis is used within my bot as a fast caching layer for server configurations. Since all server configs are stored within my PostgreSQL server, it would be faster to get it from Redis than making expensive db calls for static config values. Although LRU caches can be used or even a simple dict cache, I wish not to increase any memory usage as I want my bot to be as light as possible

  • all feature checks first check the value from Redis, and if not found, makes or updates the cache with said value and gets it from the db instead (this is the primary redis why Redis is used in the first place)

  • utils for this cogs can be found under Libs.cog_utils.config, UI components can be found under Libs.ui.config

GitHub

A multipurpose Discord bot built with freedom and choice in mind - No767/Kumiko

slate swan
#

help

final iron
slate swan
#

im figuring it out hold on bbg

slate swan
# final iron
async def join(interaction: Interaction):
    """Join the voice channel the user is in"""
    if interaction.user.voice:
        channel = interaction.user.voice.channel
        await channel.connect()
    else:
        await interaction.response.send_message("not in a voice channel")
        print(f"vc: {interaction.user.voice}")```
#

so the code, says if im in a vc, it says None, even though i am in a vc. This is an issue as it cannot tell that i am currently in a voice channel that the bot has full access to whenever it should return the voice channel im in

#

example:

slate swan
#
intents.typing = True
intents.presences = True
client = discord.Client(intents=intents)
client = run(intents=Intents.all())
    def __init__(self, *, intents: Intents):
        super().__init__(intents=intents)
        self.tree = app_commands.CommandTree(self)

    async def setup_hook(self) -> None:
        await self.tree.sync()```
#

ok guys!

slate swan
#

i love you so very much, just realized one of my intents was client = run(intents=Intents.None())

#

not all of us make mistakes like this only the ones who dont know wtf their doing ๐Ÿ’ฏ

cloud dawn
sick birch
#

Not when your IDE/editor tells you :P

quick brook
#

when you do that, it makes it just really confusing for people actually reading the code and yourself

#

for example, this is mine

class KumikoCore(commands.Bot):
    """The core of Kumiko - Subclassed this time"""

    def __init__(
        self,
        intents: discord.Intents,
        session: ClientSession,
        pool: asyncpg.Pool,
        redis_pool: ConnectionPool,
        lru_size: int = 256,
        dev_mode: bool = False,
        *args,
        **kwargs,
    ):
      ...
#

and line 4 is pretty much not needed since line 5 is already a subclass of discord.Client

#

so effectively they are the same thing

unkempt canyonBOT
#

src/bot.py lines 17 to 24

class Skurczybyk(commands.Bot):
    def __init__(self) -> None:
        self.logger = Logger(name="Skurczybyk")
        self.http_session = aiohttp.ClientSession()
        self.config = Environment()
        self.prisma = Prisma()
        super().__init__(command_prefix=".", intents=nextcord.Intents.all())```
quick brook
#

prisma?

slate swan
#

yes, prisma

quick brook
#

i used the prisma python client before and it takes like 250MB of ram

slate swan
#

so thats like nothing

quick brook
#

i just use asyncpg instead. my bot's memory went from like 250MB to 75MB

quick brook
#

my goal is to cut down memory usage as much as i can, so asyncpg made more sense

slate swan
#

makes sense

quick brook
#

plus using sql pretty much gave me all of the control when it came to writing queries. with prisma, it was so wacky and you end up being constrained with what the library offers

slate swan
#

didnt have to write so complex queries yet

sick birch
#

I hear bad things about Prisma Python client

slate swan
#

im just so amazed with the type safety and real time typehints so thought ill use it for a project

sick birch
#

Which is a shame because I really liked their TS client and I hear very good things about their Rust client

#

But I am also starting to move away from ORMs these days so pepeHmm

quick brook
#
SELECT pin.content
FROM pin_lookup
INNER JOIN pin ON pin.id = pin_lookup.pin_id
WHERE pin_lookup.guild_id=$1 AND LOWER(pin_lookup.name)=$2 OR LOWER($2) = ANY(aliases); 

this is like an example of one of mine

#

also some of my queries depend on pg_trgm, which i dont think prisma supports

slate swan
quick brook
#

yea

sick birch
#

Well their engine is in Rust

#

I think the TS client is their "flagship client"

quick brook
#

i mean i tried all sorts of orms. sqlalchemy, tortoise orm, prisma, piccolo, django orm, etc

#

didn't like any of them

slate swan
#

i cant share my opinion yet thats my first orm in python and all i tested it with were basic queries and i liked it Shrugdge

sick birch
#

ORMs are fine for basic stuff but it ends up becoming a footgun later on from my experience

quick brook
#

that

sick birch
#

One of the groups I'm part of uses an ORM and as our project got more complex we spent more and more time fighting SQLAlchemy

quick brook
#

yea. for me, i wasted a ton of time fighting the orms and spent a lot of time just reading the docs

slate swan
#

but in the end you know some sketchy methods to do stuff in it

sick birch
#

True, but you really shouldn't have to do that

slate swan
#

yeah but i guess if its really so hard to do some query you can hard code it, misses a point of the orm but yeah

#

by hard code i mean write actual SQL query in string

sick birch
#

ORMs also sometimes produce really arcane SQL that is hard to debug

#

Regardless, off topic for this channel ๐Ÿ˜…

slate swan
#

originated from discord bot ๐Ÿ˜† LIKE

subtle spade
slate swan
#

or @bot.listen()

subtle spade
#

I tried that and use command and getting this error
AttributeError: 'Client' object has no attribute 'command'

#

I use sparkedhost

quick brook
slate swan
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

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

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

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

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

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

New in version 2.0.
subtle spade
quick brook
# subtle spade Why?

Please make sure you read this fully

When you look for hosting your bot, you might be tempted to use free services or providers that claim to support hosting discord bots (eg PebbleHost and others). Do not uses them. Why? Let me explain.

Free hosts and tiers always have drawbacks - The point of a free tier or a host is to get the user to use their product, and upgrade for all of the good features. Hosts such as replit (see ?tag replit for more info) use shared cpus, oftentimes will run into ratelimits, and have "gotchas" that make you tempted to upgrade to their paid tiers. They also literally remove all control out of how you run your bot. Think about it: Hosts need to make money somehow in order to either break even or gain profit. So naturally they will tempt you into upgrading in order to do that. This is basic economics and quite literally how businesses run.

If you are still looking for a host after reading this, then you have some options. And here are them:

  1. Pay up - Pay up and use a VPS provider. My pick is Heznter, but see ?tag vps for the full list (if you are on the Python discord server, then see !hosting for your options). More than likely if you are not an eligible HS or uni student, this is your option.

  2. Self Host - If you are able to self host your own server, then go for it. This is really the only "free" way if you already pay for your electricity bill and have the equipment to do so

  3. GitHub Student Developer Pack - IF you are an eligible student in an verified HS or college (you will need to either provide an valid student ID or proof of education of your HS or college. school transcripts work in this case), then you may apply for this deal. The deal offers $200 free credits on DigitalOcean for 6 months, so if you are a student and need to host your bot, go for it.

#

Need to run your bot 24/7? Get a cheap VPS.
https://www.scaleway.com/ EU https://www.time4vps.eu/ Lithuania.
https://www.digitalocean.com/ US https://www.vultr.com/ US
https://www.ovh.co.uk/ EU/Canada https://www.hetzner.com/ Germany/US
Self-hosting: Free hosting: Kinda free:
Any computer. Heroku dead ๐Ÿฆ€ GCP, AWS have one year free micros.

Time4VPS

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

slate swan
#

!hosting

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.

subtle spade
#

Thanks guys. My codes works fine when i tried locally on my computer in visual studios

quick brook
#

ok

tall temple
#

yo please how can i use interaction.response.edit_message method for a specific embed ?

slate swan
#

this is for interaction only

#

if you want to edit message in other channel use message.edit()

final iron
#

^

#

You'd need to get the discord.Message object of the message you want to edit

tall temple
#

oh so i would just ake something like embed.edit or something likle that depending on the pycord method

final iron
#

Why use pycord though

tall temple
#

didn't notice sorry ๐Ÿ˜น

slate swan
tall temple
final iron
#

!d discord.Message.embeds

unkempt canyonBOT
tall temple
final iron
#

Returns the messages embeds

#

You can then edit/create a new one

slate swan
#

.edit(embed=updated_embed)

tall temple
#

yes that's what i thought first

tall temple
#

thanks @slate swan & @final iron

slate swan
#

blud bitwise added us

#

"added"

tall temple
#

hmm ?

slate swan
#
  1. what library is that
  2. where is this code placed. Is it inside any class
final iron
#

Pycord I think

slate swan
#

Discord on mobile be like

#

Iterally text is cutoff

final iron
#

I think your discord is just cooked lol

#

Now code formatting on mobile is a whole different conversation

slate swan
#

what build is that

final iron
#

bro idek I just click update when it needs to be updated ๐Ÿ˜ญ

#

Stable

#

If that's what you mean

slate swan
#

nope

#

settings -> scroll down

#

and you got App Version

final iron
#

192

slate swan
#

issues with being beta tester i guess

final iron
#

prob

#

They should really add code formatting on mobile

#

Very readable ๐Ÿ‘

wicked atlas
final iron
#

Radical

slate swan
#

Works for me ๐Ÿ˜Œ

#

still on pc better

final iron
#

Discord lacking for iOS mobile smh

wicked atlas
#

fr

slate swan
#

it only takes interaction

tall temple
tall temple
#

but i don't use class method so idk if that's important

slate swan
#

this is inside a View subclass using a decorator

#

you dont use this method

tall temple
#

yes

#

but how can i disable a button with the method i actually use ?

slate swan
#

i guess you can use the button object you define

#

cb

tall temple
#

cb.disable ??

slate swan
#

try

tall temple
#

no error occurs

slate swan
#

idk

#

use the subclass method then

tall temple
#

a

sly flicker
#

I need someone to help me with my simple bot

#

please @ / ping me if you can help me

twilit grotto
sly flicker
# twilit grotto send the code and error
import discord
import os
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)
# Initialize the Discord client
intents = discord.Intents.default()
client = discord.Client(intents=intents)

# Replace 'YOUR_BOT_TOKEN' with your actual bot token
BOT_TOKEN = 'YOUR_BOT_TOKEN'

@client.event
async def on_ready():
    print(f'Logged in as {client.user.name}')

@client.event
async def on_message(message):
    # Check if the message was sent by the bot itself
    if message.author == client.user:
        return

    # Check if the message content is "online" (case-insensitive)
    if message.content.lower() == "online":
        await message.channel.send('1')
    else:
        await message.channel.send('2')

# Start the bot
client.run(BOT_TOKEN)
#

I want the bot to return 1 when I send "online" in the server, otherwise I want it to return 2. This is for testing purposes

slate swan
#

And what's happening when you try it out

sly flicker
#

It only returns 2

#

No matter if I say "online" or not

sick birch
slate swan
#

(side note, don't use client and bot, pick one based on your needs and stick to it)

sick birch
#

You should never need both at once

#

Your client also appears to be missing intents

sly flicker
#

Ok so I should only import discord? I'll try that

final iron
#

What

sly flicker
#

I get that there's a proper way to do things...

final iron
#

Nobody said that

sly flicker
#

Oh you meant the intents thing, I don't know anything about that

final iron
#

discord.ext.commands.Bot is a subclass of discord.Client, so the choice is obvious

sly flicker
#

I'm really new at this

final iron
#

discord.py might seem like a beginner library, but it's not

#

Learning at least OOP and async programming is basically a requirement

sly flicker
#

I'm not really that kind of learner

#

I have a goal in mind and this is the next step

final iron
#

If you learn by making projects, make smaller projects first

sly flicker
#

I'm making a botnet

final iron
#

...

#

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

sly flicker
#

It's for my own server set

#

I need them tell me when they're online

obsidian fable
#

any way to hide a slash command for everyone except for specified User IDs

sly flicker
#

They send an online notice to the discord server and I need the bot to pick that up

#

I just don't understand how this is not a simple problem

final iron
#

It's a very simple problem, that's the problem

sly flicker
#

oh so I'm being gatekept

final iron
#

If you can't solve this problem I don't understand how you'll be able to create a whole bot

sly flicker
#

I already tried google and chatgpt so this is where I'm at

final iron
#

No? This isn't some super secret solution

#

Most people in this server aren't just going to spoonfeed you

sly flicker
#

Well why can't you share the problem. I'm working in vb.net and batch

#

I'm not paying for school just to be treated like this

twilit grotto
final iron
#

Okay, you have instances of both discord.Client and discord.ext.commands.Bot which can potentially cause issues. discord.ext.commands.Bot is a subclass of discord.Client so, you'd want to delete your Client instance and use your Bot instance

sly flicker
#

You had no idea what it was for until I said so

final iron
#

You'd also need message_content intents

sly flicker
#

I am 100% sure you haven't even tried to reproduce it

final iron
#

You don't need to reproduce the error, it's extremely clear

sly flicker
#

I don't believe in your methodology and think I it's flawed

final iron
#

I shared you the problem

sly flicker
#

I ment solution

final iron
#

I also shared the solution

sly flicker
#

Why not just update my code and paste it back to me correctly

obsidian fable
#

dont expect everyone to spoonfeed you

sly flicker
#

I'll pay for it if needed

#

Christ Jesus\

final iron
#

Well, like I said, most people aren't going to spoonfeed you

final iron
unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

sly flicker
#

I have full doubt that you even know what the solution is

final iron
obsidian fable
#

thats literally the soultion?

sly flicker
#

It's not

#

The solution would be an updated and working version of the code

obsidian fable
#

edit the code yourself

sly flicker
#

That's some, "Module could potentially cause an issue"

final iron
#

Yes, the 2 instances could potentially cause issues down the line, but I don't believe it's the issue right now (still should fix it)

final iron
sly flicker
#

@obsidian fable I doubt you even know what this is about but you're taking a side.

#

I'm seriously not here to argue

final iron
#

Your instance of discord.Message.content is probably None, therefore it's going to always respond with 2

#

!d discord.Intents.message_content

unkempt canyonBOT
#

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

โ€ข The message was sent by the client

โ€ข The message was sent in direct messages

โ€ข The message mentions the client

This applies to the following events...

final iron
#

This is the solution

final iron
#

You've been told the issue your facing, and been provided the solution

#

Do whatever you want with the information

sly flicker
#

As a side, I always spoon feed people the information

final iron
#

I guess we follow different guidelines then

sly flicker
#

I just call it being helpful... I'll see what I can do with the information you provided

final iron
#

I believe that spoonfeeding doesn't help a person learn as they will just take the code, implement it into their program and move on in 95% of cases

#

Telling somebody the issue, then providing the resources to create a solution forces a person to somewhat understand the code they're writing

sly flicker
#

Ok so deleting the client completely breaks it

final iron
#

Yes, you need to remove discord.Client and exclusively use discord.ext.commands.Bot

obsidian fable
#

you have two discord clients going on

bot = commands.Bot(command_prefix="!", intents=intents)
intents = discord.Intents.default()
client = discord.Client(intents=intents)
#

remove one of them

final iron
#

^

sly flicker
#

It wasn't working with no intents to begin with

#

Same problem I mean

obsidian fable
#

did you toggle intents in the discord developer portal

sly flicker
#

no

obsidian fable
#

do that first

sly flicker
#

ok

#

done that

final iron
sly flicker
#

so it needs intents, understood

graceful basin
#

hey, is there a way i can make it so i can make a discord bot take messages from a specific channel in another server and send those messages in my own server?

final iron
#

Data privacy and allat

#

Anyway

quiet spade
#

Hello

graceful basin
#

even though the bot isnt in the server that the messages should be retrieved from?

final iron
#

Um, no?

#

It has to be the server to see the messages

#

Okay what you're doing probably breaks TOS

#

Trying to copy messages of servers that you're not in

graceful basin
#

oh alr

final iron
#

Not gonna help with that

final iron
final iron
#

Pretty obvious imo

graceful basin
#

so i can get info about commissions from different places into my own server

quick brook
#

Privacy violations

sly flicker
#

@final iron I fixed my problem

final iron
#

Good for you

sly flicker
#
import discord
import os

intents = discord.Intents.default()
intents.typing = False
intents.presences = False
intents.message_content = True  # Enable message content intent

client = discord.Client(intents=intents)

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

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    print(f"Received message: {message.content}")

    if message.content.startswith('hello'):
        print("Detected $hello command")
        await message.channel.send('Hello!')

# Use 'TOKEN' without percent signs
client.run(os.getenv('TOKEN'))
slate swan
#

Me when people post the most random code

sly flicker
quick brook
slate swan
sly flicker
quick brook
slate swan
#

People won't try to find someone with the same issue. People are lazy and will ask

sly flicker
slate swan
#

If they don't get an answer they'll scream and not search on their own, and definitely not search in this channel LULW

sly flicker
#

I used chatgpt to solve the problem

quick brook
# sly flicker what's that?

If you need commands, use the commands extension.
Docs: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html

Why should I use the commands extension?

  • Prevents spaghetti code
  • Better performance
  • Easy handling and processing of command arguments
  • Argument type converters
  • Easy sub commands
  • Command cooldowns
  • Built-in help function
  • Easy prefix management
  • Command checks, for controlling when they're to be invoked
  • Ability to add command modules via extensions/cogs
  • Still able to do everything you can do with Client
slate swan
quick brook
sly flicker
#

Yeah it's so much more heplful then people

quick brook
#

ChatGPT is jackshit anyways

sly flicker
#

Works for me, very well

quick brook
#

Data is outdated and it's just getting dumber and dumber

slate swan
#

Love the

I fixed my problem
when you did absolutely nothing and just pasted what the AI told you cat_clown

sly flicker
#

I use persistance so it's very helpful for me

sly flicker
quick brook
slate swan
#

And then people will come back because they got some old code from that AI

sly flicker
#

Y'all sheep

quick brook
slate swan
#

Says the ๐Ÿ‘ doing like everyone and asking AI then copy paste code LULW

sly flicker
#

I'm here to exclaim my victory

#

lol

quick brook
sly flicker
#

2 hours

#

maybe 4 if you count breaks

quick brook
sly flicker
#

I couldn't care less

slate swan
#

v0.x gang

quick brook
#

nice i know someone who is in the v0.16 gang

sly flicker
#

The intents thing is weird but other than that it seems pretty straight forward

quick brook
#

ddevs wanted to kill off prefixed commands essentially

sly flicker
#

It's just for enabling extra functions right?

quick brook
#

eg message_content

sly flicker
#

Exactly yeah

#

I wish someone could have just explained that earlier like I said it was pretty straightforward I just needed to ask chatgpt

#

Google wasn't helpful either

quick brook
sly flicker
quick brook
sly flicker
#

I had gpt4 but gpt3 worked fine you just need to convince it to check its database

#

I realize that

quick brook
#

so if you are looking for v2 help, then good luck with chatgpt

sly flicker
#

It worked fine

quick brook
#

"worked fine"

sly flicker
#

You just need to convince it to break the box

quick brook
#

i hate it when people depend on chatgpt like it's life support

sly flicker
#

That's fair

slate swan
#

Welcome in 2023

quick brook
#

yep 2023 moment

sly flicker
#

I mean it's like depending on the internet but whatever

#

It's the same as depending on google

#

You probably wouldn't be much of a programmer if you couldn't read a help file online

slate swan
#

Using AI everywhere for everything. People won't bother to learn and then call themselves "Developers" or "Legendary Developer" or whatever, although all they do is ask AI

quick brook
#

anyways, you just got done with quite literally the most basics of dpy

sly flicker
#

small victory for me

quick brook
#

you've got a ton of ground to cover if you want a deeper dive

sly flicker
#

Next I'm going to have the bot download .txt files that I send to it to populate a database

quick brook
#

would suggest looking at the source code for R. Danny if you want to see the inner working of a dpy bot

quick brook
#

files are not databases

sly flicker
#

no no

#

files go into database

quick brook
#

nosql?

sly flicker
#

maybe in json?

#

no sql

#

alright you got me

quick brook
#

SQL is pretty much the de-facto standard for bots

#

why? most data that you will store for your bot are relational. here's an example: Say that i'm building an economy module for my bot. I need to store how much coins a user has, the inventory of the user, and other data. Now one user can have multiple items and jobs, and another user can have the same jobs but different items. you essentially need to build relationships between these, and that's what SQL does best

sly flicker
#

It's not going to be very complex, just the name of a machine , it's ipv4 and ipv6 address if it has one. I'll use that data later

quick brook
#

ok

#

even for less complex bots, sql also works very well

sly flicker
#

alright. I've used sql for crypto mining servers before but that's it

#

it was all software i hadn't written so i've barely touched it

quick brook
#

ok

final iron
terse knoll
#

hi. whats the problem? yesterday its fix but now not :|

glad cradle
#

do you have multiple python versions installed in your pc?

#

also calling your file Discord.py is not the best choice

wispy pasture
terse knoll
#

@glad cradle

wispy pasture
wispy pasture
# terse knoll

try reboting your pc, that usually fix the issue for me

terse knoll
#

ok

terse knoll
#

ye

#

i think my python file have problem

quick brook
quick brook
#

Your file has a backtick and the command that is running it removes it

#

Just remove the backtick and run it again

terse knoll
terse knoll
#

@quick brook i have q
how can i give roll too all members?

left dew
#

does anyone know why, when i start a tasks.looop in another loop, then close that loop, why doesnโ€™t it start the other loop. ive tested everything and it just doesnโ€™t start

buoyant quail
formal basin
#

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

harsh orbit
#
@bot.event
async def on_message(message):
  tax_channel = bot.get_channel(1145303393963872357)
  if message.channel == tax_channel:
   if "k" in message.content:
     message.content.strip("k")
     number = message.content + "000"
     await tax_channel.send(number)

Why the bot start spamming when I send 50k?

formal basin
slate swan
#

Cause you named them the same on_message

#

!e ```py

def func():
print(1)

def func():
print(2)
func()

unkempt canyonBOT
#

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

2
slate swan
#

Only the last one will actually work

#

If you wanna have many in one cog

#

Do this instead

formal basin
#

oh wait

#

nvm

slate swan
#
@listener("on_message")
async def some_cool_name(...):
  ...```
formal basin
#

ok thanks

formal basin
slate swan
#

..

#

It was just pseudo code

formal basin
#

oh ok

slate swan
#

Obviously replace it with commands.Cog.listener

formal basin
#

ik

harsh orbit
#

How I can check if is there number in message?

slate swan
#

!d str.isdigit

unkempt canyonBOT
#

str.isdigit()```
Return `True` if all characters in the string are digits and there is at least one character, `False` otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric\_Type=Digit or Numeric\_Type=Decimal.
harsh orbit
#

I thought this for check int only

#

Anyway, thx

slate swan
#

!e ```py
print("1.23".isdigit())
print("123".isdigit())

unkempt canyonBOT
#

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

001 | False
002 | True
harsh orbit
#

I need another check

#

I need if there is an number only like
50bd

slate swan
#

a number that ends with bd ?

harsh orbit
#

50 works + 50hd but bd only not

harsh orbit
slate swan
#

can you show examples

harsh orbit
#

I want if the message doesn't have number the bot delete it
Example:
If I send hs the bot will delete it
But if I send 50hs the bot will make another thing

slate swan
#
  1. does it only work with 50 or any number
  2. what are the string suffixes that work
harsh orbit
#

Nope, with any number
k & m

slate swan
#

so

123ks -> works
123ms -> works
hs -> fail
12hs -> works
``` ?
harsh orbit
#

Yup

#

And also
123 works

slate swan
#

and only those three combinations

#

ks ms hs

harsh orbit
#

Only
Digit only & digit with M & digit with k

slate swan
#

r'(?P<number>\d+)(?P<suffix>[kmh]s)' this regex might work

#

but im not sure if i understood correctly

harsh orbit
slate swan
#

!e ```py
import re

pattern = r'(?P<number>\d+)(?P<suffix>[kmh]s)'

test_strings = ["123ks", "123ms", "hs", "12hs"]

for string in test_strings:
match = re.match(pattern, string)
if match:
print(f"String: {string} - Number: {match.group('number')}, Suffix: {match.group('suffix')}")
else:
print(f"String: {string} - No match")

unkempt canyonBOT
#

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

001 | String: 123ks - Number: 123, Suffix: ks
002 | String: 123ms - Number: 123, Suffix: ms
003 | String: hs - No match
004 | String: 12hs - Number: 12, Suffix: hs
harsh orbit
#

I used another way

#

But what is this error?

harsh orbit
harsh orbit
buoyant quail
#

Looks like you are trying to reply to deleted message

harsh orbit
#

Ah

harsh orbit
#

Why the bot checking it own messages

#

How I can disable that

buoyant quail
#

Where

#

Just check if the author is the bot and skip them

slate swan
#

check if author is bot itself

buoyant quail
#

Just use a dictionary?

#

Where key is guild id

naive briar
#

!e sure :)

def command(guild_id):
    if (var := getattr(__builtins__, f"guild_var_{guild_id}", None)) is not None:
        print(var, "ye")

    else:
        setattr(__builtins__, f"guild_var_{guild_id}", {"data": f"{guild_id} thing"})
        print("No")

command(10)
command(10)

command(20)
command(20)
unkempt canyonBOT
#

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

001 | No
002 | {'data': '10 thing'} ye
003 | No
004 | {'data': '20 thing'} ye
wispy pasture
#

a stupid question:

can i store my data in a discord channel instead of a database?

slate swan
#

why would you want to do that

wispy pasture
slate swan
#

if you wanna make your life harder sure you can try

#

but i dont see a reason to not wanna use a tool that is literally created to store data

#

i understand not everyone likes SQL and vice versa but there are plenty of databases on the market

wispy pasture
vocal snow
#

what are you trying to test that would require you to do such a thing

#

you are shooting yourself in the foot

wispy pasture
left dew
#

does anyone know why, when i start a tasks.loop in another loop, then close that loop, why doesnโ€™t it start the other loop. ive tested everything and it just doesnโ€™t start

slate swan
buoyant quail
left dew
slate swan
#

no idea im not that into crypto

left dew
#

alright

#

so this tracks incoin transaction and then the confirm_checker loop doesnt seem to start, and i have no idea why```py
@tasks.loop(seconds=10)
async def incoming_trans(channel_id, message_id):
print(message_id)
channel = bot.get_channel(channel_id)
con,cur = openCON()
cur.execute(f"SELECT * FROM db WHERE channel_ID = '{channel_id}'")
i = cur.fetchall()[0]

key = PrivateKey(i['crypto_wif'])
address = i["address"]
transactions = key.get_transactions()

req_btc = shorten_btc(req_amount-0.00001656)
btc_bal = float(key.get_balance(currency='btc'))
btc_price = float(requests.get('https://blockchain.info/ticker').json()['USD']['last'])
usd_am = key.get_balance(currency='usd')
if btc_bal >= req_btc:
# msg = await channel.fetch_message(message_id)
# await msg.delete()
embed = discord.Embed(title="New Transaction", description=f"The amount of {req_amount} ({usd_am} USD) has been detected", color=discord.Color.light_grey())
embed.set_thumbnail(url="https://cdn.discordapp.com/emojis/1145663841955500042.gif?size=240&quality=lossless")
confirm_checker.start(channel.id)
print(9)
incoming_trans.stop()
print("started")

@tasks.loop(seconds=10)
async def confirm_checker(channel_id):
channel = bot.get_channel(channel_id)
on,cur = openCON()
cur.execute(f"SELECT * FROM db WHERE channel_ID = '{channel_id}'")
i = cur.fetchall()[0]

key = PrivateKey(i['crypto_wif'])

trans = key.get_transactions()

data = requests.get(f"https://blockstream.info/api/tx/{trans}").json()
print(f"https://blockstream.info/api/tx/{trans}")
status = data["status"]
confirmations = data["status"]["confirmed"]

print(1)
if confirmations == "true":
await channel.send("complete")
print(2)
print(status)
print("done")
confirm_checker.stop()
else:
print("nothing")```

slate swan
#

first of all dont use requests library in discord bot, its blocking

left dew
#

huh

slate swan
#

!blocking

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!

left dew
#

oh ok

left dew
#

and u think this might be why the second loop isnt starting?

slate swan
#

no idea just first thing i noticed

left dew
#

oh

left dew
buoyant quail
#

Do you get some errors? What output do you get from prints? Because simplified version works fine

@tasks.loop(seconds=3)
async def task1():
    global i
    i += 1
    print(i)
    if i == 3:
        task2.start()
        print("started")
        task1.stop()
        print("stopped")

@tasks.loop(seconds=3)
async def task2():
    print("+++")
1
2
3
started
stopped
+++
+++
cloud dawn
#

global ๐Ÿ—ฟ

buoyant quail
#

Testing pixels_snek_2

left dew
left dew
buoyant quail
#

Try to add a print right in the start of the function.. Maybe you got something that is taking a lot of time in that task

left dew
#

okay

tall temple
#

hey please how can i delete an interaction message like msg = await interaction.respond.send_message(. . .)

left dew
quick brook
#

If u read the docs then you would have found it pretty easily

tall temple
#

thanks

quick brook
buoyant quail
left dew
#

okay

tall temple
buoyant quail
#

You need to call it of course ducky_sus

#

It's a method

quick brook
tall temple
#

rohh

left dew
#

or canโ€™t u do await interaction.message.delete()?

buoyant quail
#

interaction.message only exists if it was runned from message

left dew
#

oh i see

#

but his is a response

left dew
radiant shuttle
#

why i can not download discord-component library in pycharn . its saying failed

#

is there another way to add buttons

slate swan
radiant shuttle
#

then how can i add buttons

turbid condor
#

It's non-compatible as far as i know

buoyant quail
#

This repository has been archived by the owner on Dec 18, 2021. It is now read-only.
It's discontinued.

turbid condor
radiant shuttle
slate swan
#

Nice code, but we don't need it

subtle spade
radiant shuttle
slate swan
#

No point, we're telling you to use discord.py instead

radiant shuttle
#

its still have the error

slate swan
#

No you're clearly not

turbid condor
radiant shuttle
buoyant quail
turbid condor
#

Move that bm channel variable to after your on_ready event inside the on_message event

slate swan
#

Look. at. the. examples.

turbid condor
subtle spade
left dew
turbid condor
#

It is an event

subtle spade
#

should it be on_command?

turbid condor
#

For commands (especially prefix commands) you need to use commands.Bot instead of discord.Client

subtle spade
#

Ok, thx. I will check that link out

turbid condor
#

This is an example

left dew
#

@buoyant quail i printed trans and it gave me ['blah blah'], woll that effect anything when i put it into data = โ€ฆ.

buoyant quail
radiant shuttle
#

Traceback (most recent call last): File "C:\Users\pirat\PycharmProjects\pythonProject\main.py", line 1, in <module> import discord File "D:\pythonProject\lib\site-packages\discord\__init__.py", line 25, in <module> from .client import Client File "D:\pythonProject\lib\site-packages\discord\client.py", line 53, in <module> from .webhook import Webhook File "D:\pythonProject\lib\site-packages\discord\webhook\__init__.py", line 11, in <module> from .async_ import * File "D:\pythonProject\lib\site-packages\discord\webhook\async_.py", line 41, in <module> from ..channel import PartialMessageable ImportError: cannot import name 'PartialMessageable' from 'discord.channel' (D:\pythonProject\lib\site-packages\discord\channel.py)

#
import discord
import random
import asyncio
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True

client = commands.Bot(command_prefix='!', intents=intents)

suits = {
    'hearts': 'โ™ฅ๏ธ',
    'clubs': 'โ™ฃ๏ธ',
    'diamonds': 'โ™ฆ๏ธ',
    'spades': 'โ™ ๏ธ'
}

numbers = list(range(2, 11))
high_value_cards = ['K', 'Q', 'J', 'A']

cards = [(number, suit) for suit in suits.keys() for number in numbers] + [(card, suit) for suit in suits.keys() for
                                                                           card in high_value_cards]

@client.event
async def on_ready():
    print('Bot is ready')
#
@client.command()
async def bj(ctx):
    channel = client.get_channel(1145730366963990619)
    if ctx.channel.id != channel.id:
        return

    if not cards:
        embedVar = discord.Embed(title="Dealer is Shuffling the deck!", color=ctx.author.top_role.color)
        shuffle_message = await ctx.channel.send(embed=embedVar)
        await asyncio.sleep(3)
        await shuffle_message.delete()
        cards.extend(
            [(number, suit) for suit in suits.keys() for number in numbers] + [(card, suit) for suit in suits.keys() for
                                                                               card in high_value_cards])
        random.shuffle(cards)

    random.shuffle(cards)
    player_hand = []
    total_sum = 0
    ace_count = 0

    # Deal the first two cards
    for _ in range(2):
        card = cards.pop()
        if card[0] in high_value_cards:
            if card[0] == 'A':
                if total_sum + 11 <= 21:
                    random_num = 11
                    ace_count += 1
                else:
                    random_num = 1
            else:
                random_num = 10
        else:
            random_num = card[0]

        player_hand.append(f"{card[0]} {suits[card[1]]}")
        total_sum += random_num

    while total_sum > 21 and ace_count > 0:
        total_sum -= 10
        ace_count -= 1

    if total_sum == 21:
        result = "Your hand: \n" + ", ".join(player_hand) + "\nTotal: " + str(total_sum) + "\nBlackjack!"
    else:
        result = "Your hand: \n" + ", ".join(player_hand) + "\nTotal: " + str(total_sum)

    hit_button = discord.ui.Button(style=discord.ButtonStyle.green, label="Hit")
    stop_button = discord.ui.Button(style=discord.ButtonStyle.red, label="Stop")

    view = discord.ui.View()
    view.add_item(hit_button)
    view.add_item(stop_button)

    embedVar = discord.Embed(description=result, color=ctx.author.top_role.color)
    await ctx.channel.send(embed=embedVar, view=view)


#
@client.event
async def on_button_click(interaction):
    if interaction.custom_id == 'hit':
        # Add your hit logic here
        pass
    elif interaction.custom_id == 'stop':
        # Add your stop logic here
        pass
#

where is the error

slate swan
#

Update to latest

#

Also

#

No such event as on_button_click

buoyant quail
#
    `# Add your stop logic here` ![ducky_sus](https://cdn.discordapp.com/emojis/987918033504854066.webp?size=128 "ducky_sus")
slate swan
#

Sounds like AI LULW

meager rock
slate swan
#

Or at least guard clauses

glad cradle
#

why everyone do client = commands.Bot ๐Ÿ˜ญ

radiant shuttle
#

i did it and still nothing

slate swan
#

Run this script

radiant shuttle
#

its working thanks you so much

slate swan
#

๐Ÿ‘

quick brook
quick brook
slate swan
#

That's why we told them to use discord.py and durch that outdated and archived package

dusk dagger
slate swan
#

crap

subtle spade
buoyant quail
#

@bot.command()

turbid condor
#

U forgot the ()

subtle spade
#

Thanks guys!

glad cradle
slate swan
#

py.discord

unkempt canyonBOT
#

examples/advanced_startup.py line 91

async with CustomBot(commands.when_mentioned, db_pool=pool, web_client=our_client, initial_extensions=exts) as bot:```
radiant shuttle
glad cradle
unkempt canyonBOT
#

discord/client.py lines 297 to 308

async def __aenter__(self) -> Self:
    await self._async_setup_hook()
    return self

async def __aexit__(
    self,
    exc_type: Optional[Type[BaseException]],
    exc_value: Optional[BaseException],
    traceback: Optional[TracebackType],
) -> None:
    if not self.is_closed():
        await self.close()```
radiant shuttle
glad cradle
#

or there's an error in your code

glad cradle
quick brook
radiant shuttle
dusk dagger
#

But yes, you have to respond to any interaction.

radiant shuttle
# dusk dagger Code?
hit_button = discord.ui.Button(style=discord.ButtonStyle.green, label="Hit")
    stop_button = discord.ui.Button(style=discord.ButtonStyle.red, label="Stop")

    view = discord.ui.View()
    view.add_item(hit_button)
    view.add_item(stop_button)

    embedVar = discord.Embed(description=result, color=ctx.author.top_role.color)
    message = await ctx.channel.send(embed=embedVar, view=view)

    try:
        interaction = await client.wait_for("button_click", check=lambda i: i.component.label in ["Hit", "Stop"], timeout=60)

        if interaction.component.label == "Hit":
            card = cards.pop()
            if card[0] in high_value_cards:
                if card[0] == 'A':
                    if total_sum + 11 <= 21:
                        random_num = 11
                        ace_count += 1
                    else:
                        random_num = 1
                else:
                    random_num = 10
            else:
                random_num = card[0]

            player_hand.append(f"{card[0]} {suits[card[1]]}")
            total_sum += random_num

            while total_sum > 21 and ace_count > 0:
                total_sum -= 10
                ace_count -= 1

            result = "Your hand: \n" + ", ".join(player_hand) + "\nTotal: " + str(total_sum)
            embedVar.description = result
            await message.edit(embed=embedVar)

        elif interaction.component.label == "Stop":
            await message.edit(content="Game stopped.", view=None)

    except asyncio.TimeoutError:
        await message.edit(content="Timeout: The game has ended.", view=None)
dusk dagger
#

What library is this?

#

Itโ€™s not an event in dpy, even if it was, I really donโ€™t think you should be overwriting the callback with it

radiant shuttle
#

can you help me with it?I'm confused

slate swan
#

Use callback

radiant shuttle
subtle spade
buoyant quail
#

Just remove the arg or give it a default value

subtle spade
#

A default value?

buoyant quail
#

Yes. As you would do in a normal function

subtle spade
#

I dont get it. Maybe I have to study it more

buoyant quail
#

Let's say you have such function

def f(x):
    return x

assert f(3) == 3
assert f() == 5

how would you achieve that by changing only the function definition? (to not get errors)

formal basin
#

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

formal basin
#

https://paste.pythondiscord.com/H6EA

Traceback (most recent call last):
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/ext/commands/bot.py", line 935, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 850, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "/Users/zagzag/vscode/zagzag/cog-folder/moderation-commands.py", line 10, in <module>
    class ModerationCog(commands.Cog):
  File "/Users/zagzag/vscode/zagzag/cog-folder/moderation-commands.py", line 25, in ModerationCog
    @app_commands.commands(name="kick", description="kicks a user (moderator only)")
TypeError: 'module' object is not callable

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

Traceback (most recent call last):
  File "/Users/zagzag/vscode/zagzag/zagzag.py", line 786, in <module>
    asyncio.run(main())
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
    return future.result()
  File "/Users/zagzag/vscode/zagzag/zagzag.py", line 782, in main
    await bot.load_extension(f'cog-folder.{filename[:-3]}')
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/ext/commands/bot.py", line 1013, in load_extension
    await self._load_from_module_spec(spec, name)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/ext/commands/bot.py", line 938, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cog-folder.moderation-commands' raised an error: TypeError: 'module' object is not callable``` im having this error
buoyant quail
#

You want @app_commands.command i guess

formal basin
#

oh

#

thanks

subtle spade
quick brook
#

as what is the "load" arg supposed to do?

#

are you interested in creating options or subcommands

subtle spade
#

Subcommands. !bm should be one command. !bm load is another one

quick brook
subtle spade
#

Yes, I know. I try to figure it out

quick brook
subtle spade
subtle spade