#discord-bots

1 messages · Page 306 of 1

left mantle
#

but it works?

slate swan
#

That's not the point

#

But sure, keep being ignorant.

#

Will go far 👍

left mantle
#

i'm not lol

#

corny

young dagger
#

Is it time to remove discriminator from my code? embed.set_author(name=f"Case {case_id} • ban • {user.name}#{user.discriminator}", icon_url=avatar_url)

slate swan
#

iirc you can just use {user}

#

It'll remove the discriminator from people that migrated to the new username system

#

There are still users out there that have a discriminator

young dagger
slate swan
#

As well as bots but your command probably isn't relevant for them

slate swan
young dagger
slate swan
#

Yeah

young dagger
#
embed.set_author(name=f"Message Deleted • {author}", icon_url=avatar_url)
NameError: name 'author' is not defined```
#

So I can't use {author}

slate swan
#

But you can use message.author smart

young dagger
#

True

young dagger
#

For some reason it includes the discriminator

slate swan
#

Latest version?

young dagger
#

message.author.name works 🤔

unkempt canyonBOT
#

discord/user.py lines 101 to 104

def __str__(self) -> str:
    if self.discriminator == '0':
        return self.name
    return f'{self.name}#{self.discriminator}'```
slate swan
#

Since it has the code that does it for you

#

So make sure you're running the latest version

unkempt canyonBOT
slate swan
#

That version

young dagger
slate swan
#

Update it then

#

python3 -m pip install -U discord.py

young dagger
#

Installing collected packages: discord.py Attempting uninstall: discord.py Found existing installation: discord.py 2.1.1 Uninstalling discord.py-2.1.1: Successfully uninstalled discord.py-2.1.1 Successfully installed discord.py-2.3.2

gilded cedar
#

so i have one task on nextcord i'm hosting the bot but for some reason 10 to 23 hours after activating the bot it gives me error of RuntimeError: task is already launched and is not completed. what is the cause?

turbid condor
#

Can u tell what the task is exactly doing?

#

As for the error it seems your task is relaunching while the previous one is still going on

gilded cedar
turbid condor
#

Can u tell where u are running this loop?

gilded cedar
#

you want me the actual code i guess?

turbid condor
gilded cedar
#

"on_ready" event

turbid condor
#

Hmm that might be the issue

unkempt canyonBOT
#
Install packages with `python -m pip`

When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.

Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.

Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.

turbid condor
#

Since on_ready can fire many times

slate swan
#

Start your task in setup_hook

turbid condor
slate swan
#

Probably has something similar, no?

#

In the end it's a d.py fork

turbid condor
#

Didn't found it so far

#

The safest option for now i guess should be using on_cog_load method

#

If he has cogs

#

Otherwise he might need a command to start the task

naive briar
turbid condor
#

This works too

wary mica
#

I made a reaction role system but when I complete it and react to the message, I don't get the role.
What did I do wrong?

#

Otherwise I can give the file if you don't recognize it

young dagger
#

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

naive briar
shrewd fjord
#
if emoji in setup_data[payload.message_id]["roles"]:
            role = setup_data[payload.message_id]["roles"][emoji]
#

you using channel id as key not message id

#

use payload.channel_id instead

wary mica
#

And where I have to change something

shrewd fjord
shrewd fjord
wary mica
#

So instead payload.message_id => payload.channel_id in Line 87 and 60 ?

wary mica
slate swan
#

how can I get the voice channel where the bot is located?

wary mica
#
        if emoji in setup_data[payload.channel_id]["roles"]:
            role = setup_data[payload.message_id]["roles"][emoji]
            await member.add_roles(role)

Really?

wary mica
slate swan
unkempt canyonBOT
slate swan
#

!d discord.VoiceClient.channel

unkempt canyonBOT
slate swan
#

!d discord.Interaction.guild

unkempt canyonBOT
slate swan
#

!d discord.Guild.voice_client

unkempt canyonBOT
#

property voice_client```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol) associated with this guild, if any.
slate swan
#

Sometimes searching yourself may be useful

#

oh, it’s work with guild?

#

just I used ctx.voice_client in command

#

but it didn't work with interaction

#

thanks!

shrewd fjord
wary mica
wary mica
shrewd fjord
wary mica
vale wing
vale wing
vale wing
wary mica
vale wing
#

With computer it will be easier to understand

#

Anyways where is your initial problem message

wary mica
#

Ok but I know what the problem is and that is with the message id and channel id

vale wing
#

Nvm found it

slate swan
#

how can i add a thubnail to my embed?

vale wing
#

To add a role, you first need to get the Role object via its ID

role = guild.get_role(role_id)

Only then add it

await member.add_roles(role)
vale wing
unkempt canyonBOT
#

set_thumbnail(*, url)```
Sets the thumbnail for the embed content.

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

Changed in version 1.4: Passing `None` removes the thumbnail.
wary mica
#

There are no error messages but the reaction role just doesn't work and it should be the problem with the channel id or message ud

slate swan
vale wing
#

🤦‍♂️

#

Person who never learned python detected

slate swan
#

lol

#

That's a first

vale wing
#

You must enclose this into quotes, and that's keyword-only arg fyi

slate swan
#

im so dumb

#

fr ik

wary mica
slate swan
#

aaaand another error

vale wing
#

My name contains "spoon feeder" but uh I'm not really one

vale wing
slate swan
#

ok so what do i do

vale wing
#

set_thumbnail(url="whatever")

vale wing
slate swan
#

ok thanks

#

can u fix my last error?

vale wing
slate swan
#

its not exactly an error

#

there are no errors but some lines of codes dont work

vale wing
#

Which ones

slate swan
#

ill explain to u

#

so

vale wing
#

Nah you better just show the lines

#

That will be much faster

wary mica
# vale wing Add this to line #80 and give me the output ```py print(setup_data[payload.messa...
Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
    start(fakepyfile,mainpyfile)
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
    exec(open(mainpyfile).read(),  __main__.__dict__)
  File "<string>", line 85
    if emoji in setup_data[payload.message_id]["roles"]:
IndentationError: unexpected indent

[Program finished]
slate swan
#

i have a ticket system that makes you select a ticket category and you can select support or application. if u select a support it sends in the support ticket channel an embed but in the application channel it wont

#

but i made it to send it

vale wing
slate swan
#

want me to send u the code?

vale wing
#

There are many reasons code doesn't get run and I can't tell without the code lol

vale wing
slate swan
#

like it ignores this line of code

vale wing
#

Because it is not in the function

#

Have yall ever heard of indents cmon

slate swan
#

yeah

vale wing
#

!indents

unkempt canyonBOT
#
Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

slate swan
#

i know how to use indents

vale wing
#

Just put it inside

#

What code editor do you use

slate swan
#

replit

vale wing
#

What device do you have

slate swan
#

pc

vale wing
#

You're on the wrong path

#

But I am going to guide you into right

wary mica
vale wing
#

@slate swan ^

vale wing
#

Trust me your coding experience is going to be much better

vale wing
slate swan
#

i prefer replit for a lot of reasons

vale wing
#

Replit is absolute garbage for code editing

slate swan
#

like secrets

vale wing
#

You make .env file and place all secrets there

slate swan
vale wing
#

In pycharm you can just make run config

slate swan
#

i use replit only for bots

vale wing
slate swan
#

i use vs code for anything else

vale wing
#

The only good thing about replit is you can use some language without installing whole environment for it

vale wing
#

Don't tell me you're hosting them with replit

slate swan
#

but i got no money for other platforms

slate swan
#

still not working

vale wing
glad cradle
#

@vale wing

#

go test my PR brr

vale wing
#

Nah imma go play accordion 🤗

slate swan
glad cradle
vale wing
#

Got 4 pages of Cherney etude (I hate it) to learn

wary mica
slate swan
#

OHHH

#

I FOUND IT

slate swan
#

cool

slate swan
vale wing
slate swan
#

just add backticks around text

vale wing
#

The only piece I don't hate is Mozart's sonata a minor 🤗

#

But anyways that's offtopic

glad cradle
unkempt canyonBOT
#

@glad cradle :white_check_mark: Your 3.11 eval job has completed with return code 0.

hi this is a really long text but separated in multiple lines... but remember to put some spaces otherwise the text will all show up without spaces
vale wing
#

I'm not gonna check your PR today probably sorry

glad cradle
slate swan
#

fire the project manager

vale wing
#

Idk if I can fire myself

glad cradle
#

i can fire you

vale wing
#

Who's gonna make goofy ahh promotional videos after I get fired?

shrewd fjord
#

bros pros

slate swan
#

How can I host a bot 24/7 for free?

#

So keep it online

quick brook
quick brook
# slate swan How can I host a bot 24/7 for free?

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 use 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 college 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. Raspberry Pis oftentimes are great for this.

  3. GitHub Student Developer Pack - IF you are a enrolled student in an HS or college (you will need to either provide an valid student ID or proof of education of your HS or college), then you may apply for this deal. More info about this can be found here. The deal offers $200 free credits on DigitalOcean for 1 year, so if you are a student and need to host your bot, go for it.

normal jasper
#

Hi, I have two discord bots ( 2 python scripts in a folder ), Is it possible for me to run both of them, by executing only one of them? Like I want to run the first bot, and it executes the second bots script and runs that one too

quick brook
normal jasper
#

when running the first bot

#

but it doesnt work since the first one stops working

quick brook
#

you can't run two bots with one script FYI

normal jasper
#

but I only want to start one

#

and it starts the other one automaticcly

quick brook
#

that's why we have something called process managers. systemd is what you will find across most linux distros

normal jasper
#

there is no way?

quick brook
slate swan
quick brook
#

that's why systemd exists.... to manage processes. there is even one for windows iirc

sick birch
#

I use it to spin up multiple containers at once, ie a discord bot, Postgres database, web dashboard all at once

#

It can also show you logs from all containers

slate swan
#

Or its private project

sick birch
#

!src

unkempt canyonBOT
sick birch
#

Bot, web, snekbox, Redis, and some other I can't think off the top of my head

slate swan
#

Okay ill check it out

quick brook
#

no

sick birch
#

Yes, though not recommended

#

Actually hrmm

#

It would only get registered after you call the command

#

So it probably wouldn't work the way you expect it to

#

Can you give us more context?

#

What exactly are you trying to make?

quick brook
#

PK?

sick birch
#

You will probably want a list/set of "registered users"
In each on_message you'd check if the user who sent that message is in that list/set of registered users
If they are, delete their message, and replace it with the message from the webhook

quick brook
#

PluralKit?

#

sounds extremely simliar to what pk does

#

the way pluralkit handles it is just to sub out the message from the system with their current alter

#

it's all webhooks believe it or not

left mantle
#

just made ping command, anyone know why its outputting NaN? ```py
@commands.command(name="ping")
async def ping(self, ctx):
embed = discord.Embed(title="Pong! :ping_pong:",description=f"{client.latency * 1000} ms")
await ctx.reply(embed=embed)

unkempt canyonBOT
#

discord/client.py lines 323 to 330

@property
def latency(self) -> float:
    """:class:`​float`​: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds.

    This could be referred to as the Discord WebSocket protocol latency.
    """
    ws = self.ws
    return float('nan') if not ws else ws.latency```
quick brook
#

np

vocal laurel
#

!source

unkempt canyonBOT
quick brook
#

r danny?

vocal laurel
#

No no I mean how it shows the code in discord instead of pressing the link

quick brook
unkempt canyonBOT
#

bot/exts/info/code_snippets.py line 81

async def _fetch_github_snippet(```
vocal laurel
#

Uh what..

vocal laurel
#

Why won’t it show snippet??

vale wing
#

Too long

grim echo
slate swan
#

hay i need a helo

grim echo
slate swan
#
  File "c:\Users\Prasa\Downloads\discord-bot\main.py", line 38, in <module>
    bot = discord.Bot(command_prefix="*", activity=activity, status=discord.Status.online)
          ^^^^^^^^^^^
AttributeError: module 'discord' has no attribute 'Bot'
PS C:\Users\Prasa\Downloads\discord-bot> ```
#

any one help please

#

@elfin island

grim echo
slate swan
grim echo
slate swan
#

hm

slate swan
#

in line no 38 bot = discord.Bot(command_prefix="*", activity=activity, status=discord.Status.online)

naive briar
#

!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.
upbeat otter
#

You'll have issues since they both use the same namespace

digital sleet
#

How would one control a discord bot with subscriptions as in if it was in a guild and the subscription ran out would stop working

dim trellis
#

!e

unkempt canyonBOT
#
Missing required argument

code

#
Command Help

!eval [python_version] <code, ...>
Can also use: e

Run Python code and get the results.

This command supports multiple lines of code, including formatted code blocks. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

The starting working directory /home, is a writeable temporary file system. Files created, excluding names with leading underscores, will be uploaded in the response.

If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside them.

Currently only 3.11 version is supported.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!

dim trellis
#

!e @bot.command()
async def ban(ctx, member: discord.Member, *, reason=None):
if ctx.author.guild_permissions.ban_members:
await member.ban(reason=reason)
await ctx.send(f'{member.display_name} has been banned.')
else:
await ctx.send("You don't have permission to ban members.")

unkempt canyonBOT
#

@dim trellis :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     @bot.command()
004 |      ^^^
005 | NameError: name 'bot' is not defined
left dew
#

anyone know why this sometimes wont remove the appended user?
users_oncooldown = []

        if interaction_1st.user.id in users_oncooldown:
            await interaction_1st.response.send_message(content=f"**Slow Down! You're on cooldown.**", ephemeral=True)
            return
        else:
            users_oncooldown.append(interaction_1st.user.id)  ```
```py
          try:
            users_oncooldown.remove(interaction_1st.user.id)
          except ValueError:
            pass```
quick brook
#

And you can set it to be on a per-user basis

left dew
final iron
#

!d discord.ext.commands.cooldown

unkempt canyonBOT
#

@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command)

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType).

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown) is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error) and the local error handler.

A command can only have a single cooldown.
final iron
#

It’s a decorator

left dew
#

oh i see

graceful ermine
#

Hey, I'm trying to see how I can fetch a message ID can anyone could help me and see what I am doing wrong in my code?

    @app_commands.command(name="start-giveaway", description="starts a giveaway")
    @app_commands.checks.has_permissions(manage_guild=True)
    async def giveaway(self, interaction: discord.Interaction, title: str, description: str, hour: int):


        embed = discord.Embed(
            title=title,
            description=description
        )

        embed.set_author(name=f"Started by {interaction.user.mention}", icon_url=interaction.user.avatar.url)




        
        embed.add_field(name="Ends at:", value=f"<t:{hour*60}:r> ")
        embed.set_footer(text= f"ends at {hour} hours from now!")


        message = await interaction.response.send_message(embed=embed)


        message2 = await interaction.channel.fetch_message(message)

        await message2.add_reaction(emoji=":tada:")



        await asyncio.sleep(hour*60)


        new_message = await interaction.channel.fetch_message(message.id)


        users = await new_message.reactions[0].users().flatten()

        users.pop(users.index(self.bot.user))


        winner = random.choice(users)


        await interaction.response.send_message(f"Congratulations {winner.mention} of winning the {title} {description} giveaway!!")
naive briar
#

And if you're using discord.py, reaction.users().flatten() is not a thing anymore

graceful ermine
slate swan
#

.users is an async iterator

#

!d discord.Reaction.users

unkempt canyonBOT
#

async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) representing the users that have reacted to the message.

The `after` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake) abc.

Changed in version 2.0: `limit` and `after` parameters are now keyword-only.

Examples

Usage...
shrewd fjord
unkempt canyonBOT
#

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

Fetches the original interaction response message associated with the interaction.

If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message) or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).

Repeated calls to this will return a cached value.
graceful ermine
naive briar
#

It's written in plain English

graceful ermine
#

Oh, sorry, I misread it

hushed galleon
#

if you want the message sent by your response, use the Interaction.original_response() method

#

oops im blind spooky already said that

hushed galleon
#

just after calling send_message(), you can use original_response() to get the message object

graceful ermine
#

so like this message = await interaction.response.send_message(interaction.original_response())

#

@hushed galleon

hushed galleon
#

i mean on the next line, not as an argument to send_message()

graceful ermine
#

Oh sorry

hushed galleon
#

don't forget to await it too

graceful ermine
#

I'm aware

graceful ermine
hushed galleon
graceful ermine
#

I'm confused by "do not return the sent message"

hushed galleon
#

they likely meant that send_message() returns None, which isn't all that useful to you

graceful ermine
#

like, messages2 = interaction.original_response?

hushed galleon
#

er sure, call the function and await it so it returns an InteractionMessage object, then you can assign it and add your reaction

graceful ermine
#

Ok

graceful ermine
#

I have this error now for some reasom, I never used interaction.original_response() before

hushed galleon
#

can you paste the full traceback?

graceful ermine
#
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 827, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\berka\Desktop\New folder (2)\cogs\giveaway.py", line 49, in giveaway
    message2 = await interaction.channel.fetch_message(message)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\abc.py", line 1624, in fetch_message
    data = await self._state.http.get_message(channel.id, id)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 745, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In message_id: Value "<InteractionMessage id=1155937234344755332 channel=<TextChannel id=1066505917929111587 name='〖📄〗rules' position=4 nsfw=False news=False category_id=1066505917929111585> type=<MessageType.chat_input_command: 20> author=<Member id=1155904972123287653 name='Stellar Utilities' global_name=None bot=True nick=None guild=<Guild id=1066505915584495618 name='Eagle Defense Sys (Dev Environment)' shard_id=0 chunked=True member_count=12>> flags=<MessageFlags value=0>>" is not snowflake.```
hushed galleon
#

you don't need to fetch the message again, original_response() already returns an InteractionMessage object

graceful ermine
#

Oh

#

Okay makes sense now

hushed galleon
graceful ermine
# hushed galleon its explained in the documentation here too

It works now, but how could I fix this error? Traceback (most recent call last): File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 827, in _do_call return await self._callback(self.binding, interaction, **params) # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\berka\Desktop\New folder (2)\cogs\giveaway.py", line 43, in giveaway users = await message.reactions[0].users().flatten() ~~~~~~~~~~~~~~~~~^^^ IndexError: list index out of range

        await interaction.response.send_message(embed=embed)
        
        message = await interaction.original_response()
        
        await message.add_reaction("🎉")
        
        await asyncio.sleep(hour*60)
        
        users = await message.reactions[0].users()```
hushed galleon
#

oh right i missed that in your initial snippet

#

original_response() gives you a message from the API rather than the real-time gateway, which won't update as your bot receives reaction events

#

you can either find the message in Client.cached_messages (and also make sure you have messages and reactions intents enabled for said events to be received), or you can re-fetch the message

#

as per the docs original_response() will return the same message object if you call it again, so in this case it would be appropriate to use channel.fetch_message()

graceful ermine
graceful ermine
#

@hushed galleon Hey, I have used interaction.channel.fetch_message() and I have been going into the same last error Traceback (most recent call last): File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 827, in _do_call return await self._callback(self.binding, interaction, **params) # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\berka\Desktop\New folder (2)\cogs\giveaway.py", line 57, in giveaway await interaction.channel.fetch_message(message) File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\abc.py", line 1624, in fetch_message data = await self._state.http.get_message(channel.id, id) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 745, in request raise HTTPException(response, data) discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In message_id: Value "<InteractionMessage id=1155953522697838642 channel=<TextChannel id=1066505917929111587 name='〖📄〗rules' position=4 nsfw=False news=False category_id=1066505917929111585> type=<MessageType.chat_input_command: 20> author=<Member id=1155904972123287653 name='Stellar Utilities' global_name=None bot=True nick=None guild=<Guild id=1066505915584495618 name='Eagle Defense Sys (Dev Environment)' shard_id=0 chunked=True member_count=12>> flags=<MessageFlags value=0>>" is not snowflake.

#
    @app_commands.command(name="start-giveaway", description="starts a giveaway")
    @app_commands.checks.has_permissions(manage_guild=True)
    async def giveaway(self, interaction: discord.Interaction, title: str, description: str, hour: int):


        embed = discord.Embed(
            title=title,
            description=description
        )

        embed.set_author(name=f"Started by {interaction.user.mention}", icon_url=interaction.user.avatar.url)




        
        embed.add_field(name="Ends at:", value=f"<t:{hour*60}:r> ")
        embed.set_footer(text= f"ends at {hour} hours from now!")


        await interaction.response.send_message(embed=embed)
        

        message = await interaction.original_response()



        await message.add_reaction("🎉")



        await asyncio.sleep(6)


        await interaction.channel.fetch_message(message)

        users = await message.reactions[0].users()

        users.pop(users.index(self.bot.user))


        winner = random.choice(users)

shrewd apex
#

!d discord.TextChannel.fetch_message

unkempt canyonBOT
#

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

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) from the destination.
shrewd apex
#

u need to pass id of message

#

and also readding message which is returned

slate swan
#

why you need to fetch message when you already have it?

graceful ermine
#

which is something like this

#
Traceback (most recent call last):
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 827, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\berka\Desktop\New folder (2)\cogs\giveaway.py", line 59, in giveaway
    async for user in message.reactions[0].users():
                      ~~~~~~~~~~~~~~~~~^^^
IndexError: list index out of range

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

Traceback (most recent call last):
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'start-giveaway' raised an exception: IndexError: list index out of range
slate swan
#

it means there are no reactions?

graceful ermine
#

I was trying to code it where the program doesn't pick the bot when picking random users

#

for the giveaway

lunar vine
#

i need HELP

#
class UserIdentificationView(View):
    def __init__(self, timeout=180):
        super().__init__(timeout=timeout)

    @Button(label="Sender", style=ButtonStyle.gray)
    async def sender_button(self, button, interaction):
        member = interaction.user
        await interaction.response.edit_message(
            content=f"User Identification\nSender: {member.mention}; Receiver: Blank"
        )

    @Button(label="Receiver", style=ButtonStyle.gray)
    async def receiver_button(self, button, interaction):
        member = interaction.user
        await interaction.response.edit_message(
            content=f"User Identification\nSender: Blank; Receiver: {member.mention}"
        )```

member = interaction.user
AttributeError: 'Button' object has no attribute 'user'
#

@sick birch ^

buoyant quail
#

Your button is interaction object and interaction is button object

unkempt canyonBOT
#

examples/views/confirm.py lines 29 to 30

@discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):```
lunar vine
#
class UserIdentificationView(View):
    def __init__(self, timeout=999):
        super().__init__(timeout=timeout)

    @discord.ui.button(label="Sender", style=discord.ButtonStyle.gray)
    async def sender_button(self, button:discord.ui.Button, interaction):
        member = interaction.user
        await interaction.message.edit(
            content=f"User Identification\nSender:{member.mention} Receiver: Blank"
        )

    @discord.ui.button(label="Receiver", style=discord.ButtonStyle.gray)
    async def receiver_button(self, button:discord.ui.Button, interaction):
        member = interaction.user
        await interaction.message.edit(
            content=f"User Identification\nSender: Blank; Receiver: {member.mention}"
        )``` @buoyant quail
buoyant quail
#

still the same

#

if you typehint it as discord.ui.Button it won't become button

lunar vine
#

i have button:discord.ui.Button

buoyant quail
#

it still will be an interaction

#

arguments have their order

lunar vine
#

then what do i do here

buoyant quail
#

change the order of arguments

lunar vine
#

i try lemon_angrysad

#

let me see if it work

#

omg it worked nice but i have an issue sadly

#

it wont go into the embed! why is it ontop of it @buoyant quail

buoyant quail
#

?
I don't see any embeds in the code you provided

lunar vine
#
            identification_embed = discord.Embed(
            title="User Identification",
            color=0xff00b3
            )
            identification_embed.add_field(name="Sender:", value="Blank")
            identification_embed.add_field(name="Receiver:", value="Blank")
            user_identification_view = UserIdentificationView()
            message = await interaction.channel.send(embed=identification_embed, view=user_identification_view)
#

sorry it just said the error was on that part so i didnt know

#

this is line 218-225

#

that was line 32-48

buoyant quail
#

You have both values as Blank here
Why would something else be there

lunar vine
buoyant quail
#

Then change not the content but the embed

lunar vine
#

thats the sentence for this

lunar vine
buoyant quail
#
        member = interaction.user
        await interaction.message.edit(
            content=f"User Identification\nSender:{member.mention} Receiver: Blank"
        )

You are editing the message. Not the embed.

lunar vine
#

ya! im asking for what to use instead of content! sir !

buoyant quail
#

embed=...

#

with the new embed object

lunar vine
#

oh i need to make a seperated embedobject?

#

like embed=embednew

buoyant quail
#

you can use the same and edit only a field inside it
or yes, a separate one

lunar vine
#

field.edit?

buoyant quail
#

~~```py
embed.fields[0].value = "new value"

#

hmm

#

it looks it actually doesn't work like this

#
embed.set_field_at(0, name="new name", value="new value")
#

here is the correct version

graceful ermine
#

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



    
class button(discord.ui.View):
        def __init__(self):
            super().__init__(timeout=None)
        
@discord.ui.Button(label="Join", style= discord.ButtonStyle.blurple)
async def regen(self, button: discord.ui.Button, interaction: discord.Interaction):
    ...


    

    @app_commands.command(name="start-giveaway", description="starts a giveaway")
    #@app_commands.checks.has_permissions(manage_guild=True)
    async def giveaway(self, interaction: discord.Interaction, title: str, description: str, hour: int, role: Optional[discord.Role] = None):

        ETA = int(time.time() + hour*3600)


        embed = discord.Embed(
            title=title,
            description=description
        )

        embed.set_author(name=f"Started by {interaction.user.mention}", icon_url=interaction.user.avatar.url)


        view = button()

        
        embed.add_field(name="Ends at:", value=f" <t:{ETA}:R> ")
        embed.set_footer(text= f"ends at {hour} hours from now!")


        await interaction.response.send_message(embed=embed, view=view)
        



        await asyncio.sleep(12)



        users = []
        async for user in view:
            users.append(user)

        users = [user for user in users if user != self.bot.user]

        winner = random.choice(users)
        response_message = f"Congratulations {winner.mention} on winning the {title} {description} giveaway!!"


        if role:
            await user.add_roles(role)




        await interaction.followup.send(response_message)



    


async def setup(bot):
    await bot.add_cog(giveaway(bot)) ```
#

How could I code it where it picks someone random to win a giveaway from pressing a button?

final iron
#

Why is there so much spacing

#

Holy shit

#

Your indentation is also cooked

#

You need to fix that

final iron
#

You've already done it

#

Are you actually just asking how to create a button?

vocal laurel
lunar vine
#

whats 0, whats the numbers signling

#

maybe ill just debug over wnd over and figure it out or give docs

#

@buoyant quail u said place this at content= or message.edit

graceful ermine
final iron
graceful ermine
final iron
#

Obviously

#

It's sample code

#

You've done it before, why are you asking how to do it lmao

graceful ermine
lunar vine
#

looks like it should work perfectly whats the issue exactly @graceful ermine

graceful ermine
lunar vine
#

so you didn't test out your code, but came to ask for help..

mighty pilot
#

Bruh

lunar vine
#

test it out and lmk

graceful ermine
lunar vine
#

what reaction

mighty pilot
#

The Main difference between reaction giveaways and button giveaways is that you can't check the reactions on the message, you can alternatively store it in a list... like you are currently with that code

lunar vine
#

can you point to me where reactions are mentioned in the code

mighty pilot
#

He was referring to earlier when it was mentioned that he's done it before

#

I think

lunar vine
#

i see

mighty pilot
#

Funny stuff though. Code works fine still wants help

lunar vine
#

lol, it's all good, atleast he learned something

graceful ermine
# lunar vine lol, it's all good, atleast he learned something

Button doesn't work

  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 827, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\berka\Desktop\New folder (2)\cogs\giveaway.py", line 70, in giveaway
    async for user in view:
TypeError: 'async for' requires an object with __aiter__ method, got button

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

Traceback (most recent call last):
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'start-giveaway' raised an exception: TypeError: 'async for' requires an object with __aiter__ method, got button```
final iron
#

Fix your formatting

#

There's no reason it should take 2 screens worth of text

#

Makes it very difficult to read

lunar vine
#

lemme see

graceful ermine
#
class button(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
                
    
    @discord.ui.button(label="Join", style= discord.ButtonStyle.blurple)
    async def regen(self, button: discord.ui.Button, interaction: discord.Interaction):
            ...


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

    @app_commands.command(name="start-giveaway", description="starts a giveaway")
    @app_commands.checks.has_permissions(manage_guild=True)
    async def giveaway(self, interaction: discord.Interaction, title: str, description: str, hour: int, role: Optional[discord.Role] = None):

        ETA = int(time.time() + hour*3600)


        embed = discord.Embed(
            title=title,
            description=description
        )
        embed.set_author(name=f"Started by {interaction.user.mention}", icon_url=interaction.user.avatar.url)
        view = button()
        embed.add_field(name="Ends at:", value=f" <t:{ETA}:R> ")
        embed.set_footer(text= f"ends at {hour} hours from now!")
        await interaction.response.send_message(embed=embed, view=view)
        await asyncio.sleep(12)



        users = []
        async for user in view:
            users.append(user)

        users = [user for user in users if user != self.bot.user]

        winner = random.choice(users)
        response_message = f"Congratulations {winner.mention} on winning the {title} {description} giveaway!!"
        if role:
            await user.add_roles(role)
        await interaction.followup.send(response_message)

async def setup(bot):
    await bot.add_cog(giveaway(bot)) ```
final iron
#

Also, you cannot just iterate over a Button

#

view is not a list of users

#

It is your button instance

lunar vine
#

no way

final iron
#

:/

graceful ermine
#

i'm so brain dead

final iron
#

Honestly, this reeks of a copied tutorial

#

Originally designed for reactions, then adjusted for buttons

lunar vine
#

cough gpt

graceful ermine
#

I have been working on this bot for the past 6 hours

final iron
mighty pilot
#

You need to send your user list into the view and append it there when the button is pushed

final iron
#

Like pep8 etc

lunar vine
#

for ur user in users

#
for user in users```
final iron
#

That would just be iterating over an empty list

mighty pilot
#

Lots of using going on

#

Don't need a for loop

graceful ermine
lunar vine
final iron
mighty pilot
lunar vine
#

oh

mighty pilot
#

I wish I had a good example for this, I'm in the middle of upgrading my giveaway bot but I'm going much more complex

mighty pilot
graceful ermine
#

and if it's not then it could skip that line of code

mighty pilot
#

Well you're gonna want to add that to winner not user once you figure out how you're managing the list of members who entered

graceful ermine
mighty pilot
#

Yup

#

No reactions to iterate over

graceful ermine
# mighty pilot Yup

I'm getting this error

  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 827, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\berka\Desktop\New folder (2)\cogs\giveaway.py", line 61, in giveaway
    response_message = f"Congratulations {winner.mention} on winning the ```{title} {description}``` giveaway!!"
                                          ^^^^^^^^^^^^^^
AttributeError: 'list' object has no attribute 'mention'

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

Traceback (most recent call last):
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'start-giveaway' raised an exception: AttributeError: 'list' object has no attribute 'mention'

I'm getting this error because it seems like the button isn't storing the user id

#

class button(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
                
    
    @discord.ui.button(label="Join", style= discord.ButtonStyle.blurple)
    async def regen(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message("You have joined the giveaway goodluck!")

        users = [interaction.user]
        users.append(users)


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

    @app_commands.command(name="start-giveaway", description="starts a giveaway")
    @app_commands.checks.has_permissions(manage_guild=True)
    async def giveaway(self, interaction: discord.Interaction, title: str, description: str, hour: int, role: Optional[discord.Role] = None):

        ETA = int(time.time() + hour*3600)


        embed = discord.Embed(
            title=title,
            description=description
        )
        embed.set_author(name=f"Started by {interaction.user.mention}", icon_url=interaction.user.avatar.url)
        view = button()
        embed.add_field(name="Ends at:", value=f" <t:{ETA}:R> ")
        embed.set_footer(text= f"ends at {hour} hours from now!")
        await interaction.response.send_message(embed=embed, view=view)
        await asyncio.sleep(12)
        users = []
        users.append(users)

        users = [user for user in users]

        winner = random.choice(users)
        response_message = f"Congratulations {winner.mention} on winning the {title} {description} giveaway!!"
        if role:
            await winner.add_roles(role)
        await interaction.followup.send(response_message)```
pliant jay
#

I have code for making google search's in a discord bot what site would I use for this?

graceful ermine
pliant jay
mighty pilot
mighty pilot
#

I meant @[]

graceful ermine
#

for some reason the button isn't storing the user

mighty pilot
#

What you need to do is forget about for loops, move your users list up to the top and when you declare the view=button() make it view=button(users) then get your button ready to expect that list. Then in your callback you want to do something along the lines of users.append(interaction.user.id) if you're trying to store an ID

mighty pilot
#

And you need to pass that list into the view __init__

pliant jay
final iron
#

He just sent some random shit for some reason

pliant jay
#

was very confused

final iron
#

It's a tool to manage APIs, literally nothing to do with what you want

pliant jay
#

what should I use?

final iron
pliant jay
final iron
#

Well it's an API

#

It works in any language

pliant jay
#

okay that you

final iron
#

Seems easier

graceful ermine
# mighty pilot This is a very basic version of what you need to do with the button, only this s...

What am I doing wrong?

    def __init__(self, users):
        super().__init__(timeout=None)
        self.users = users
    
    @discord.ui.button(label="Join", style= discord.ButtonStyle.blurple)
    async def regen(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message("You have joined the giveaway goodluck!")

        user2 = [self.users]
        user2.append(self.users)


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

    @app_commands.command(name="start-giveaway", description="starts a giveaway")
    @app_commands.checks.has_permissions(manage_guild=True)
    async def giveaway(self, interaction: discord.Interaction, title: str, description: str, hour: int, role: Optional[discord.Role] = None):

        users = []
        users.append(users)

        users2 = [user for user in users]

        ETA = int(time.time() + hour*3600)

        embed = discord.Embed(
            title=title,
            description=description
        )
        embed.set_author(name=f"Started by {interaction.user.mention}", icon_url=interaction.user.avatar.url)
        view = button(users2)
        embed.add_field(name="Ends at:", value=f" <t:{ETA}:R> ")
        embed.set_footer(text= f"ends at {hour} hour(s) from now!")
        await interaction.response.send_message(embed=embed, view=view)
        await asyncio.sleep(12)
       

        winner = random.choice(users2)
        response_message = f"Congratulations {winner.mention} on winning the {title} {description}giveaway!!"
        if role:
            await winner.add_roles(role)
        await interaction.followup.send(response_message)```
final iron
#

???

graceful ermine
final iron
#

Great, and that's part of the issue

mighty pilot
#

You're appending the list with itself

pliant jay
final iron
#

If you're following that tutorial you'd be using a separate library, not aiohttp

final iron
#

Did you read the tutorial

pliant jay
#

kinda lol

#

let me read it again

final iron
#

Okay, and did it tell you to use BeautifulSoup?

pliant jay
#

yes

final iron
#

So...

pliant jay
#

so yes

final iron
#

Good

graceful ermine
#

nvm

#

I got it

naive swan
#
def write_char(data):
 with open("config.json", "w") as f:
       json.dump(data, f, indent=4)


@bot.command()
async def промпт(ctx, *, args):
 try:
    with open("config.json") as personality:
        data = json.load(personality)
        temp = data["context"]
        y = {"discord_name": f"{ctx.author.name}", "personality": f"{args}"}
        temp.append(y)

    write_char(data)
    await ctx.send("Сработало")
 except Exception as e:
    await ctx.send(f"Нихуя: {e}")

this code doesn't work, for some reason. im not getting any response from the bot, or any errors in the console.

naive swan
turbid condor
#

Do you have an error handler?

naive swan
#

yes? i guess

turbid condor
#

I mean the on_command_error event

naive swan
#

oh, nope

turbid condor
#

Weird

#

Can u send the whole code

#

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

turbid condor
#

Or you can try using print statements to see at which point the code stops working

turbid condor
#

Change @bot.event decorator above it to @bot.listen()

naive swan
#

still not getting any errors 🤔

naive briar
naive swan
naive briar
#

You don't know what doesn't work? I can't help if I don't know what the problem is

naive swan
#

you see, i'm trying to edit json file through a discord command, but that just simply doesn't work. i'm not getting any errors, so i don't think i can debug it in any way.

naive briar
#

Right

#

You don't have the message_content intent enabled

#

!message_content

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.

naive swan
#

command still doesn't work, and still no errors

naive briar
#

Did you enable the intent?

shrewd fjord
#

!on-message-event

unkempt canyonBOT
#
The discord.py `on_message` event

Registering the on_message event with @bot.event will override the default behavior of the event. This may cause prefix commands to stop working, because they rely on the default on_message event handler.

Instead, use @bot.listen to add a listener. Listeners get added alongside the default on_message handler which allows you to have multiple handlers for the same event. This means prefix commands can still be invoked as usual. Here's an example:

@bot.listen()
async def on_message(message):
    ...  # do stuff here

# Or...

@bot.listen('on_message')
async def message_listener(message):
    ...  # do stuff here

You can also tell discord.py to process the message for commands as usual at the end of the on_message handler with bot.process_commands(). However, this method isn't recommended as it does not allow you to add multiple on_message handlers.

If your prefix commands are still not working, it may be because you haven't enabled the message_content intent. See /tag message_content for more info.

shrewd fjord
#

dem

naive swan
#

i did

#

i dont think intents are the problem here

turbid condor
# unkempt canyon

You need the message_content intent inorder for the commands to work and read this too

#

And if after this the bot still doesn't respond then check your bot permissions

idle lantern
#

how to get ids for slash command that gets changed very often? and are probably different in every server?

slate swan
unkempt canyonBOT
#

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

Fetches the application’s current commands.

If no guild is passed then global commands are fetched, otherwise the guild’s commands are fetched instead.

Note

This includes context menu commands.
slate swan
#

if for whatever reason you're syncing your commands very frequently (which you probably shouldn't be doing, but that's another discussion) then the sync method will also return your list of AppCommands

idle lantern
slate swan
#

I believe you only need to sync them when the command's signature (name, set of arguments etc) changes, but not when it's callback changes

#

so ideally you'd have a text-based command that can be used to manually sync them when needed

idle lantern
#

but i would also need to restart the bot in order to change or update things right? so that basically resyncs them each time doesnt it?

meager rock
civic schooner
#

hey, so i'm using mocks to manipulate my bot in certain ways. however, mock isn't garbage collected.
this is leading to memory leaks, and i operate a big bot - so it is an issue.
i don't know if there's any way to move mocks to garbage collection, because right now it is keeping references to the mock objects
here's my implementation: https://pastebin.com/iwCuW651
any ideas?

carmine viper
#

I am converting my discord bot over from ctx commands to slash commands. Having an issue getting my reaction emojis to work, can someone point me to the right place in the discord.py library to read up on this? Below is an image of the code being used with ctx commands, just kind of stumped on this.

slate swan
#

!d discord.Interaction.original_response

unkempt canyonBOT
#

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

Fetches the original interaction response message associated with the interaction.

If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message) or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).

Repeated calls to this will return a cached value.
slate swan
#

And you'll get an interaction message that you can react to

carmine viper
#

Going through the docs, I ended up finding this (image attached) but it still isn't working. I will probably come back to this later, thanks for the info.

#

Here's where I was finding this info

slate swan
#

Not just a class name

#

How it is supposed to know what interaction you talking about

carmine viper
#

I am just a bit confused because it is inside of the function. Maybe I need more coffee. lol

#

Appreciate the responses, I will be doing more reading today. This bot was working fine what I was using ctx commands, the slash commands are new to me but something I want to impliment.

#

I may just use buttons since I can get those to work, was trying to stay as close to the original as possible, which had the reaction emojis.

shrewd fjord
unkempt canyonBOT
#

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

Fetches the original interaction response message associated with the interaction.

If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message) or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).

Repeated calls to this will return a cached value.
shrewd fjord
#

to get the messae object

#

then use add_reaction

slate swan
#

look what type it returns

#

Exactly what you are looking for

shrewd fjord
#

hmm

slate swan
#

talking to @carmine viper

shrewd fjord
#

why the code smells like gpt FR_sus

carmine viper
shrewd fjord
carmine viper
#

That's the typical response I get from this community when asking questions, lol. Which is why I am trying to use AI as a teacher.

#

Appreciate the pointers guys, I won't take up anymore of your time.

shrewd fjord
#

oh wait chatgpt dont know anything about dpy interaction yet, its old 💀

onyx elk
onyx elk
carmine viper
austere vale
#
    @nextcord.slash_command(description="Bans a user. Please specify the reason and the number of seconds of their message history that you want deleted. The minimum is 0 and the maximum is 604800 (7 days).")
    @application_checks.has_permissions(ban_members=True)
    async def ban(self, interaction, user: nextcord.User, *, reason=None, delete_message_seconds=None):
        try:
            await user.send(f"You have been banned from the server `{user.guild}` because of: \n `{reason}`.")
            await interaction.send(f"I have DMed {user.mention} that they have been banned for: `{reason}`")
        except Exception:
            await interaction.send("Failed to DM the user, oh well.")
        await interaction.guild.ban(user=user, reason=reason, delete_message_seconds=delete_message_seconds)
        embed = nextcord.Embed(
            title="Banned User",
            description=f"I have successfully banned `{user}` \n Reason: `{reason}` \n Number of seconds of their message history deleted: {delete_message_seconds}",
            color=0xFD9FA1,
        )
        await interaction.send(embed=embed)

Could someone please help me with this error?

0|main  | Ignoring exception in on_interaction
0|main  | Traceback (most recent call last):
0|main  |   File "/usr/local/lib/python3.8/dist-packages/nextcord/client.py", line 512, in _run_event
0|main  |     await coro(*args, **kwargs)
0|main  |   File "/usr/local/lib/python3.8/dist-packages/nextcord/client.py", line 2023, in on_interaction
0|main  |     await self.process_application_commands(interaction)
0|main  |   File "/usr/local/lib/python3.8/dist-packages/nextcord/client.py", line 2064, in process_application_commands
0|main  |     if app_cmd.is_interaction_valid(interaction):
0|main  |   File "/usr/local/lib/python3.8/dist-packages/nextcord/application_command.py", line 2380, in is_interaction_valid
0|main  |     return _recursive_subcommand_check(data, our_payload)  # type: ignore
0|main  |   File "/usr/local/lib/python3.8/dist-packages/nextcord/application_command.py", line 2295, in _recursive_subcommand_check
0|main  |     return _option_check(inter_options, cmd_options)
0|main  |   File "/usr/local/lib/python3.8/dist-packages/nextcord/application_command.py", line 2344, in _option_check
0|main  |     for (
0|main  | ValueError: too many values to unpack (expected 2)
quick brook
austere vale
#

Oh, is the description too long?

quick brook
#

isn't that too long?

austere vale
#

Ok let me try to change it. im not sure what the limit is on that

glad cradle
#

iirc it's 100

quick brook
austere vale
#

Oh i see. okay that seemed to fix it, thank you

quick brook
#

np

austere vale
#

actually, how would i go about setting an option description?

quick brook
austere vale
#

i dont think that there is an example here

austere vale
#

Oh i missed that. thanks so much

quick brook
#

np

quick brook
#

y

lunar vine
#

@buoyant quail u here?

#

can someone tell me where to put python embed.set_field_at(0, name="new name", value="new value") bc this code shud be effecting the embed, so the embed is below the code, but if i put it above it; the view wont be defined..

class UserIdentificationView(View):
    def __init__(self, timeout=999):
        super().__init__(timeout=timeout)

    @discord.ui.button(label="Sender", style=discord.ButtonStyle.gray)
    async def sender_button(self, interaction, button:discord.ui.Button):
        member = interaction.user
        await interaction.message.edit(
            content=f"User Identification\nSender:{member.mention} Receiver: Blank"
        )

    @discord.ui.button(label="Receiver", style=discord.ButtonStyle.gray)
    async def receiver_button(self, interaction, button:discord.ui.Button):
        member = interaction.user
        await interaction.message.edit(
            content=f"User Identification\nSender: Blank; Receiver: {member.mention}"
        )```
#

@quick brook

quick brook
lunar vine
#

this server isnt real

#

everyone here is an ai generated person with an ai generated personality

#

i refuse to change my mind

quick brook
lunar vine
#

clearly i was being sarcastic

quick brook
lunar vine
#

proof ^

lunar vine
lunar vine
#

aaaa

lunar vine
#

oki!

#

im honestly scared of getting verbally tarnished but one moment

#

ill put it on the paste bin for this server

#

@final iron ^^^^^^

final iron
lunar vine
#

😋

#

let me try this!!!

quick brook
#

you know interaction checks exists right

lunar vine
#

she*

lunar vine
lunar vine
final iron
lunar vine
#

i did it by doing this;

class UserIdentificationView(View):
    def __init__(self, timeout=999):
        super().__init__(timeout=timeout)

    @discord.ui.button(label="Sender", style=discord.ButtonStyle.gray)
    async def sender_button(self, interaction, button:discord.ui.Button):
        member = interaction.user
        embed = interaction.message.embeds[0]
        embed.set_field_at(0, name="Sender", value=member.mention)
        await interaction.message.edit(embed=embed)

    @discord.ui.button(label="Receiver", style=discord.ButtonStyle.gray)
    async def receiver_button(self, interaction, button:discord.ui.Button):
        member = interaction.user
        embed = interaction.message.embeds[0]
        embed.set_field_at(1, name="Receiver", value=member.mention)
        await interaction.message.edit(embed=embed)```
quick brook
lunar vine
#

anyway i used python embed = interaction.message.embeds[0] after looking thru and doing sum research

quick brook
lunar vine
#

receiver:@lunar vine sender: blank
embed was here

#

so i just fixed it so now it does this

#

👍 it works now, it just says my name twice cuz i pressed da button twice (both buttons)

quick brook
#

Ok

slate swan
#
import requests
import json
import time

# Configure your e621 API settings
e621_base_url = "https://e621.net/posts.json"
api_key = "e621 api key here"  # Get your API key from e621

# Specify the tags you want to search for
tags = "paws"

# Configure your Discord webhook URL
discord_webhook_url = "url here"

# Define the request headers
headers = {
    "e621 user here": "YourAppName/1.0 (by YourUsername)",
    "Authorization": f"Basic {api_key}",
}

# Create a query string with the specified tags
query_string = f"tags={tags}"

while True:
    # Make a request to the e621 API
    response = requests.get(f"{e621_base_url}?{query_string}", headers=headers)

    # Check if the request was successful
    if response.status_code == 200:
        # Parse the JSON response
        data = json.loads(response.text)
        
        # Extract and send the posts to the Discord webhook
        for post in data:
            post_url = f"https://e621.net/posts/{post['id']}"
            image_url = post["file"]["url"]
            
            # Create a payload for the Discord webhook
            discord_payload = {
                "content": f"New e621 post with tags: {tags}\n{post_url}",
                "embeds": [{"image": {"url": image_url}}],
            }
            
            # Send the payload to the Discord webhook
            response = requests.post(discord_webhook_url, json=discord_payload)
            
            # Check if the webhook request was successful
            if response.status_code == 204:
                print(f"Posted e621 image to Discord: {image_url}")
            else:
                print(f"Failed to post e621 image to Discord: {response.status_code}")
    else:
        print(f"Failed to fetch e621 posts: {response.status_code}")
    
    # Sleep for 5 seconds before the next iteration
    time.sleep(5)

don’t judge i’m still learning (somewhat ai generated 😭)

#

i can’t figure that out

quick brook
#

And your code is blocking

#

Use __A__iohttp

__A__iohttp is an __a__synchronous HTTP Client/Server for Python. Best suited for __a__sync projects like discord.py. Documentation

Blocking

Libraries like requests and urllib can block the event loop for a period of time (until the request is finished/timed out).
The bot will not respond to anything (commands, etc).

Example

async with aiohttp.ClientSession() as cs:
    async with cs.get('https://httpbin.org/json') as res:
        # usually the status code (res.status) - 
        # - is checked before calling these
        # and optionally also the content type (res.content_type)

        # bytes? ---
        # data = await res.read()
        # text? (html, etc) ---
        # data = await res.text()
        # json? ---
        # in this case it's json
        data = await res.json()
        # data is a python dict{} here
        author = data['slideshow']['author']
        print(author)
slate swan
#

ah okay

#

gonna figure smth out with aiohttp

#

thanks 🙏🏾

quick brook
#

Np

#

Also ChatGPT is complete ass for learning dpy. Since the data is from 2021

slate swan
#

i used writesonic for help, kinda sucks but up to date

sick birch
mighty pilot
#

It's probably my favorite thing when people ask some ai thing how to make something in d.py and wonder why it doesn't work. They're alright at some simple coding but imo garbage at complex stuff

slate swan
#
import aiohttp
import json
import asyncio

# Configure your e621 API settings
e621_base_url = "https://e621.net/posts.json"
api_key = "api key"  # Get your API key from e621

# Specify the tags you want to search for
tags = "paws"

# Configure your Discord webhook URL
discord_webhook_url = "the url"

# Define the request headers
headers = {
    "User-Agent": "YourAppName/1.0 (by YourUsername)",
    "Authorization": f"Basic {api_key}",
}

async def fetch_e621_posts():
    while True:
        # Create a query string with the specified tags
        query_string = f"tags={tags}"

        async with aiohttp.ClientSession(headers=headers) as session:
            # Make a request to the e621 API
            async with session.get(f"{e621_base_url}?{query_string}") as response:
                if response.status == 200:
                    # Parse the JSON response
                    data = await response.json()

                    # Extract and send the posts to the Discord webhook
                    for post in data['posts']:
                        post_url = f"https://e621.net/posts/{post['id']}"
                        image_url = post["file"]["url"]

                        # Create a payload for the Discord webhook
                        discord_payload = {
                            "content": f"New e621 post with tags: {tags}\n{post_url}",
                            "embeds": [{"image": {"url": image_url}}],
                        }

                        # Send the payload to the Discord webhook
                        async with session.post(discord_webhook_url, data=discord_payload) as webhook_response:
                            if webhook_response.status == 204:
                                print(f"Posted e621 image to Discord: {image_url}")
                            else:
                                print(f"Failed to post e621 image to Discord: {webhook_response.status}")
                else:
                    print(f"Failed to fetch e621 posts: {response.status}")

        # Sleep for 5 seconds before the next iteration
        await asyncio.sleep(5)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(fetch_e621_posts())

is this any better (still erroring x3)

mighty pilot
#

What's the error say

slate swan
mighty pilot
#

That seems like a problem connecting to that sites api

#

Did you input an api key towards the top of your code there or are you trying to run it as you pasted it here

slate swan
#

i put the api key username etc

#

when i leave it as user-agent i get a 401 error

slate swan
mighty pilot
#

Well this one's out of my comfort zone Idkchu if it was some problem with d.py I'd be of better assistance. Maybe someone else will pop in with more knowledge or you could open a #1035199133436354600 channel

golden portal
#

tbh 403 just means it's forbidden, could be your auth

slate swan
#

it was the headers part causing that error, onto the next error!

quick brook
slate swan
#

christ

quick brook
#

So you can getting 429 ratelimited

slate swan
#

what about 400

quick brook
slate swan
#

i think this has something to do with console being blown up

quick brook
#

Replit uses shared IPs which lead to heavy ratelimits. Just locally develop on your own machine (or GH codespaces)

#

Or by using NixOS or Vagrant or Docker

#

Gonna be making an NixOS config for dpy development soon sooooooo

slate swan
#

python is gonna be the end of me

#

and my 200mb of storage left

quick brook
# slate swan python is gonna be the end of me

Gonna have to determine what stuff to remove. Thus, I strongly recommend you to develop locally. Gonna be a lot easier and at the very least you aren't running GCC and compiling python w/ C headers

#

GCC 13.2.1

slate swan
#

can i run with vsc?

quick brook
#

That's what I do

quick brook
#

Feel free to reach out to me if you need help (just state that you are from the Python server and explicitly provide all of the materials and questions you need help with)

#

Better yet would be to ask your questions on the dpy server

slate swan
#

400 and 429 error on vsc 😋

slate swan
coral mirage
#

Hello, I have a question. How I can connect Discord Bot with GS. That way I can use Google Sheet as a database. Those anyone knows the steps?

sick birch
coral mirage
sick birch
#

Probably. Though not recommended at all
If you like the tabular format, use an SQL database. Even SQLite will be millions of times faster and easier to work with

coral mirage
#

I know, I use those db, but I wanted to do a favor to a mate.

It's just a google sheet that members can store rss and their information from a game.

sick birch
#

Yeah, it's possible. Google sheets does have an API

coral mirage
#

I tried eveyhting, but I can't connect for a reason it keeps saying it doesn't have enough scopes. I authorize all scopes and still nothing.

coral mirage
#

I created new credentials and tried the whole process again

sick birch
#

Does it say what scopes are missing?

coral mirage
#

no, my code says it's missing scopes.

final iron
final iron
coral mirage
coral mirage
#

its as server account

#

when creating credentials

#

I share the email as well from credentials.json

final iron
coral mirage
# sick birch Does it say what scopes are missing?

Error connecting to Google Sheets: {'code': 403, 'message': 'Request had insufficient authentication scopes.', 'errors': [{'message': 'Insufficient Permission', 'domain': 'global', 'reason': 'insufficientPermissions'}], 'status': 'PERMISSION_DENIED', 'details': [{'@type': 'type.googleapis.com/google.rpc.ErrorInfo', 'reason': 'ACCESS_TOKEN_SCOPE_INSUFFICIENT', 'domain': 'googleapis.com', 'metadata': {'service': 'drive.googleapis.com', 'method': 'google.apps.drive.v3.DriveFiles.List'}}]}

coral mirage
#

I can show you my code to maybe is wrong.

#

However I dont think so

final iron
#

I'm going to bed, but just confirm you created the service account properly

#

Here's a page from google on it

final iron
#

I'm also using a different library though

quick brook
#

Even if it's for your friend, I strongly recommend storing your data using SQL instead of gsheets. With gsheets, you will very quickly run into ratelimits and use the uses of your API key extremely quickly

#

I see no reason why not to use SQLite or Postgres in this case

coral mirage
quick brook
coral mirage
quick brook
#

Bc with gs, you aren't really learning anything new

coral mirage
#

MYSQL

quick brook
quick brook
coral mirage
#

I'll check those 2 tho.

quick brook
sick birch
# coral mirage I use SQLite.

SQLite is the database engine
asqlite and aiosqlite are Python libraries that allow you to communicate with an underlying SQLite database

faint rapids
#

How can I host a discord bot online forever?

quick brook
coral mirage
faint rapids
#

Is it free?

coral mirage
#

nop, but is super cheap.

quick brook
#

My pick goes to Henzter

coral mirage
coral mirage
#

but for my partner I'll use SQLite for him since is super light.

sick birch
coral mirage
sick birch
#

Also wrt hosts - DO's kubernetes is cheap (especially if you're a student) and you can run bots, web sites, pretty much anything

coral mirage
#

Alright guys thanks for you'll help! Have a goodnight !

#

I mean sparked has been good for me for over a year. I only pay 2 dollars.

quick brook
#

Gn. I pay $20 for mine since I'm running other software on my server as well

slate swan
#

bots can see user status right?

#

if so is it implemented w/ d.py?

naive briar
unkempt canyonBOT
#

property status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str) instead.
naive briar
slate swan
#

mhh yeah

formal basin
#
async def check_exists(self,key):
      redis = await aioredis.create_redis_pool('redis://zagzag:password@redis-11943.c56.east-us.azure.cloud.redislabs.com/11747462')
      exists = await redis.exists(key)
      redis.close()
      await redis.wait_closed()
      return exists```

aioredis has no atribute to create_redis_pool
shrewd fjord
#

!pip aioredis

unkempt canyonBOT
unkempt canyonBOT
#

docs/examples/commands.py lines 17 to 29

async def redis_pool():
    # Redis client bound to pool of connections (auto-reconnecting).
    redis = aioredis.from_url(
        "redis://localhost", encoding="utf-8", decode_responses=True
    )
    await redis.set("my-key", "value")
    val = await redis.get("my-key")
    print(val)


if __name__ == "__main__":
    asyncio.run(main())
    asyncio.run(redis_pool())```
shrewd fjord
topaz steppe
#

how I can get the message in dm of the bot

#

like @novel apex

haughty quest
#

Anyone know what the circled symbol is? Specifically its unicode, but just a name would help me find it in the unicode charts. Been striking out for a while.

vocal laurel
#

If you search it up there is a vid on how to do it

vocal laurel
#

#

Wait nvm

dreamy dune
#

I made my own emoji for it

naive briar
#

!charinfo └

unkempt canyonBOT
shrewd fjord
#

#

└ catty
└ cool

meager rock
#

big L

shrewd fjord
#

3 big L

cinder horizon
#
@bot.event
async def on_ready():
    for filename in os.listdir('./cogs'):
      if filename.endswith('.py'):
        await bot.load_extension(f'cogs.{filename[:-3]}')
        print(f'Loaded {filename[:-3]}')

error that m gettin
RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited

final iron
#

You should be doing it in setup_hook

shrewd fjord
#

!d discord.ext.commands.Bot.add_cog

unkempt canyonBOT
#

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

Adds a “cog” to the bot.

A cog is a class that has its own event listeners and commands.

If the cog is a [`app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group) then it is added to the bot’s [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) as well.

Note

Exceptions raised inside a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog)’s [`cog_load()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.cog_load) method will be propagated to the caller...
shrewd fjord
#

its coro

faint rapids
#

I want to learn discord bot in python. How can I start?

hushed galleon
# faint rapids I want to learn discord bot in python. How can I start?

if you want to use discord.py for your bot, check out their documentation and read the examples
others have more links they can provide, but there are a bunch of infamously outdated stackoverflow and youtube resources because discord.py has went through major changes recently

it's a pretty large library so start off with simple bots and gradually build up, and also if you're not too familiar with python, the most helpful thing to understand is object oriented programming since discord.py makes a lot of use of objects and methods (you can learn from the official python tutorial, find reputable youtube channels, or ask around for more links or books to read)
see also this gist on learning discord.py

gaunt marsh
#

hello
i have a problem with running my instapy bot
i have this msg
FileNotFoundError: [WinError 3] Le chemin d’accès spécifié est introuvable: 'C:\Users
\AppData\Local\Temp\tmpqowlut3o'

gaunt marsh
#

Workspace in use: "C:/Users/Ahmed/InstaPy"
OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
INFO [2023-09-27 14:30:10] [faresgraphics] Session started!
oooooooooooooooooooooooooooooooooooooooooooooooooooooo
INFO [2023-09-27 14:30:10] [faresgraphics] -- Connection Checklist [1/2] (Internet Connection Status)
WARNING [2023-09-27 14:30:11] [faresgraphics] - Internet Connection Status: error
...........................................................................................................................
CRITICAL [2023-09-27 14:30:11] [faresgraphics] Unable to login to Instagram! You will find more information in the logs above.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

INFO [2023-09-27 14:32:52] [faresgraphics] Sessional Live Report:
|> No any statistics to show

Unable to remove profile specific paths.
Traceback (most recent call last):
File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python311\Lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 217, in quit
rmtree(self.profile.path)
File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python311\Lib\shutil.py", line 759, in rmtree
return _rmtree_unsafe(path, onerror)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python311\Lib\shutil.py", line 603, in _rmtree_unsafe
onerror(os.scandir, path, sys.exc_info())
File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python311\Lib\shutil.py", line 600, in _rmtree_unsafe
with os.scandir(path) as scandir_it:
^^^^^^^^^^^^^^^^
FileNotFoundError: [WinError 3] Le chemin d’accès spécifié est introuvable: 'C:\Users\Ahmed\AppData\Local\Temp\tmpqowlut3o'

final iron
gaunt marsh
#

"I need assistance, that's why I didn't know where to ask the question.

final iron
gaunt marsh
#

thanks

tight obsidian
#

What are some popular open-source/source-available Discord bots? Other than @novel apex

#

Doesn't have to be in Python, but that would be preferable

slate swan
formal basin
#

@shrewd fjord

async def check_exists(self, key):
     
    # Redis client bound to pool of connections (auto-reconnecting).
      redis = aioredis.from_url(
        "redis://default:password@redis-11943.c56.east-us.azure.cloud.redislabs.com:11943", encoding="utf-8", decode_responses=True
    )
      
      val = await redis.exists(key)
      return val
      

key = f'antibadwords:{message.guild.id}'
               exists = await self.check_exists(key)
               if exists:

#

with this error too @shrewd fjord

2023-09-27 16:25:50 ERROR    discord.client Ignoring exception in on_message
Traceback (most recent call last):
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "/Users/zagzag/vscode/zagzag/cog-folder/auto-mod.py", line 145, in badwordsp
    exists = await self.check_exists(key)
  File "/Users/zagzag/vscode/zagzag/cog-folder/auto-mod.py", line 42, in check_exists
    val = await redis.exists(key)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/aioredis/client.py", line 1082, in execute_command
    conn = self.connection or await pool.get_connection(command_name, **options)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/aioredis/connection.py", line 1416, in get_connection
    await connection.connect()
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/aioredis/connection.py", line 703, in connect
    await self.on_connect()
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/aioredis/connection.py", line 770, in on_connect
    auth_response = await self.read_response()
RuntimeError: coroutine ignored GeneratorExit
slate swan
formal basin
slate swan
#

so optimized

fleet nymph
#

hey

#

i need some help

sick birch
#

We can't help unless we know what you need help with

fleet nymph
#

i coded a bot

#

and i got this message "discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead."

#

but i gave it admin so this shouldnt appear right?

final iron
#

lmao

#

You’ve enabled an intent in your code that wasn’t enabled in the dashboard

fleet nymph
#

it has admin

rapid knoll
#

how do you get the user of a commands.Context (ctx)?

formal basin
final iron
#

Intents are different from permissions

#

Literally read the error, and follow what it says

final iron
unkempt canyonBOT
fleet nymph
#

i thought its another word for permissions

final iron
fleet nymph
#

but thanks though

obsidian fable
#

is there any way to prevent buttons from expiring?

naive briar
#

Buttons don't expire

obsidian fable
naive briar
#

That happens when you don't respond to the button's interaction

obsidian fable
#

the button works, but it doesnt after some time

slate swan
#

maybe you set timeout to view

naive briar
#

Did you set its timeout? Because discord.py will not handle its interaction once it timeouted

obsidian fable
#

I dont think I did

naive briar
#

!d discord.ui.View

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
naive briar
#

The default timeout is 180 seconds

obsidian fable
#

I only did view = ui.View()

slate swan
#

then it will work for 3 minutes

obsidian fable
#

can I make it last forever?

naive briar
#

Set it to none

slate swan
#

set timeout to None

obsidian fable
#

let me see

quick brook
slate swan
#

Doesn't have to be in Python, but that would be preferable

quick brook
#

K

quick brook
slate swan
quick brook
#

K

glad cradle
#

LMFAO

quick brook
#

Didn't have to repeat that when I already saw it

shrewd apex
#

sigh

glad cradle
#

asher hi

shrewd apex
#

sup

shrewd fjord
#

su gey

haughty quest
haughty quest
quick brook
haughty quest
quick brook
#

more than likely it's a custom image they uploaded for an emoji

sick birch
#

?

young dagger
#

Nvm

snow coral
#

hey! how would i put text up here?

sick birch
snow coral
lunar vine
#

anyone know the thing to wait_for a button being pressed b4 moving onto da next part of da code?

#

if so just reply to this msg bc im going 2 bed ill respond tmrw

final iron
#

I hate the whole button wait_for implementation

#

It's so stupid

#

Doesn't make sense

turbid condor
#

Can't u use the interaction response for that should be better

formal basin
#
async def check_exists(self, key):
        
      
         async with self.bot.redis.client() as redis2:
           val = await redis2.exists(key)
           return val
``` Here is the code for everytime the func is tiggered it connects
#

how can I only connect once

shrewd apex
#

make a connection pool reuse that

quick brook
#

Make a connection pool

glad cradle
quick brook
silk bobcat
#
import discord
from discord.ext import commands

# Bot instance
bot = commands.Bot(command_prefix='!')

# Define your intents
intents = discord.Intents.default()
intents.message_content = True  # Enable message content for commands

# Event handler 
@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}({bot.user.id})')

# Define a command
@bot.command()
async def hello(ctx):
    await ctx.send(f'Hello, {ctx.author.mention}!')

# Run bot
bot.run('token') ```
#

i dont understand why my bot isnt running and yes i replaced token the the actual token

silk bobcat
#

yes

#

File "C:\Users\name\OneDrive\Skrivebord\Discord.bots\bot.py", line 5, in <module>
bot = commands.Bot(command_prefix='!')

#

TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'

silk bobcat
shrewd fjord
#

!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.
silk bobcat
shrewd fjord
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.

fiery girder
#
@bot.event
async def on_reaction_add(reaction, user):
    if not user.bot:
        try:
            db.execute('SELECT * FROM reaction_roles WHERE message_id = ?', (reaction.message.id,))
        except:
            pass
        for row in db.fetchall():
            if reaction.emoji == row[4]:
                await user.add_roles(discord.Object(row[3]))
                await user.send(f"You Have Been Given The {row[3]} Role")
            
@bot.event
async def on_reaction_remove(reaction, user):
    if not user.bot:
        db.execute('SELECT * FROM reaction_roles WHERE message_id = ?', (reaction.message.id,))
        for row in db.fetchall():
            if reaction.emoji == row[4]:
                await user.remove_roles(discord.Object(row[3]))
                await user.send(f"You Have Been Removed From The {row[3]} Role")
    

reaction Role isnt working

noble crane
#

!persistent

final iron
#

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

fiery girder
#

it just not detecting the reactuin

final iron
fiery girder
#

i made try causei taught uts gonna give error if the message id not exist

#

just a sec i just opened my pc

final iron
#

Just do an if statement to check if it’s None

#

It shouldn’t be erroring if it doesn’t exist

fiery girder
#

i taught it will anyways

final iron
#

Taught?

mighty pilot
#

None is different than nothing

final iron
#

?

fiery girder
#

ok done lemme check it

#

still dont work

fiery girder
final iron
#

!d discord.on_reaction_add

unkempt canyonBOT
#

discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message_edit), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add) instead.

Note

To get the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Reaction.message).

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

Note

This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add) if you need this and do not otherwise want to enable the members intent.
final iron
#

Read the docs

fiery girder
#
Traceback (most recent call last):
  File "C:\Users\abbas\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "d:\Projects\Python\FedxD Manager\main.py", line 143, in on_reaction_add
    if reaction.emoji == row[4]:
                         ~~~^^^
IndexError: tuple index out of range
#

it gave this error but i got 4 rows in my table

fiery girder
#

cause i put a print command and it worked

noble crane
#
from discord.ext import commands
import discord
import re


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

    @commands.command()
    async def dropdown(self, ctx):
        # Create a select menu
        select = discord.ui.Select(
            custom_id="dropdown_menu",
            placeholder="Select an option",
            options=[
                discord.SelectOption(label="Option 1", value="option_1"),
                discord.SelectOption(label="Option 2", value="option_2"),
                discord.SelectOption(label="Option 3", value="option_3"),
            ],
        )

        # Create a persistent view to handle the interaction
        view = discord.ui.View()
        view.add_item(select)

        # Send a message with the select menu
        message = await ctx.send("Please select an option:", view=view)

        # Define a callback function for the select menu
        async def callback(interaction):
            selected_option = interaction.data["values"][0]
            embed = None

            # Create different embeds based on the selected option
            if selected_option == "option_1":
                embed = discord.Embed(title="Option 1", description="This is Option 1's embed.")
            elif selected_option == "option_2":
                embed = discord.Embed(title="Option 2", description="This is Option 2's embed.")
            elif selected_option == "option_3":
                embed = discord.Embed(title="Option 3", description="This is Option 3's embed.")

            # Send the embed as a follow-up message with ephemeral set to True
            await interaction.response.send_message(embed=embed, ephemeral=True)

        # Set the callback for the select menu
        select.callback = callback

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

I want to make this select drop down menu work even after the bot restarts

fiery girder
#
db.execute('CREATE TABLE IF NOT EXISTS reaction_roles'
                '(message_id INTEGER, channel_id INTEGER, role_id INTEGER, emoji TEXT)')
mighty pilot
fiery girder
#

this is the table it got 4 values

#

i am dumb af

mighty pilot
#

If you're looking for row 4 you'll use [3]

fiery girder
#

WHY AM I SO DUMB

#

anyways lemme check it now

fiery girder
#

it still dont work

#

this time it gave no error

#

it didnt have give the print

#

does the bot stop caring about old messages after it is restarted?

#

cause i thing thats the case

noble crane
mighty pilot
mighty pilot
noble crane
mighty pilot
noble crane
mighty pilot
#

You just have to give the view a custom ID and timeout of None then add it in your setup hook

#

Once you do that, it won't register a view you already have, but once you send it with those criteria it'll be persistent through restarts

noble crane
#

I've been trying to do this for the past 2 hours

reef trail
#

consider going to the dpy server for more help

reef trail
mighty pilot
reef trail
#

The dpy server also has a lot of tags that are pretty useful

mighty pilot
#

True

noble crane
#

Yeah i've had a look but clearly no one is helping mate

fiery girder
# mighty pilot What's your code look like after you took out try and excepts
async def on_reaction_add(reaction, user):
    if not user.bot:
        print("reaction add")
        db.execute('SELECT * FROM reaction_roles WHERE message_id = ?', (reaction.message.id,))           
        for row in db.fetchall():
            if reaction.emoji == row[3]:
                await user.add_roles(discord.Object(row[2]))
                await user.send(f"You Have Been Given The {row[2]} Role")
            
@bot.event
async def on_reaction_remove(reaction, user):
    if not user.bot:
        print("reaction remove")
        db.execute('SELECT * FROM reaction_roles WHERE message_id = ?', (reaction.message.id,))
        for row in db.fetchall():
            if reaction.emoji == row[3]:
                await user.remove_roles(discord.Object(row[2]))
                await user.send(f"You Have Been Removed From The {row[2]} Role")```
mighty pilot
#

That may be the issue

fiery girder
#

lets test