#discord-bots

1 messages ยท Page 183 of 1

simple plume
#

I enable this on the website

cold sonnet
#

oh yeah that makes sense

#

add in code

#

!intents

unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

cold sonnet
#

but the bot part is just client for u

simple plume
#

Gonna test it

simple plume
simple plume
#

worked ty

scarlet aurora
#

Can someone help?

#

how can I check who has reacted to a message in cog.listener payload

fading marlin
#

What event are you listening to?

scarlet aurora
#

on_raw_reaction_add

#

so basically my problem is that my bot sends a message and auto adds a โœ… and โŽ reaction, then this listener needs to wait until someone reacts with either yes or no

#

but it already detects the tick that's been added by the bot itself

fading marlin
#

Does the reaction listener need to be persistent? Or should it only work for a some time?

scarlet aurora
#

I want it to timeout after like 15 mins

#
if str(payload.emoji) == "\U00002705":```
#

that's the check in the cog listener

fading marlin
#

!d discord.ext.commands.Bot.wait_for consider using this instead

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the **first event that meets the requirements**...
fading marlin
#

There's an example in the docs on how you'd implement a reaction if you need that

scarlet aurora
#

@fading marlin

#

I don't use client so what would I use instead of here I forgot

#

client.wait_for

#

is it self.wait_for ?

fading marlin
#

Wdym?

scarlet aurora
#
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)```
fading marlin
#

Looks good to me?

scarlet aurora
#

I'm not using client

#

I'm using bot

fading marlin
#

Then replace client for bot ๐Ÿคท

scarlet aurora
#

@fading marlin

#

why does it run it like 3 times

fading marlin
#

Why does what run what thrice

#

Send your code please

scarlet aurora
#

when you react with yes

#
    @commands.Cog.listener()
    async def on_raw_reaction_add(self, payload):
        if payload.channel_id == 1065720365021679718:
            channel = self.bot.get_guild(payload.guild_id).get_channel(payload.channel_id)
            message = await channel.fetch_message(payload.message_id)

            for user in message.mentions:
                i = user

            def check(reaction, user):
                return user == i and str(reaction.emoji) == '\U00002705'

            try:
                reaction, user = await self.bot.wait_for('reaction_add', timeout=60.0, check=check)
            except asyncio.TimeoutError:
                await channel.send('๐Ÿ‘Ž')
            else:
                await channel.send('๐Ÿ‘')

                for user in message.mentions:```
fading marlin
#

Ok nevermind, what I send isn't gonna be useful for your case. To answer your question, you can check if payload.user_id is equal to the ID of the bot

#

!d discord.RawReactionActionEvent this is the type of payload

unkempt canyonBOT
#

class discord.RawReactionActionEvent```
Represents the payload for a [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") or [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") event.
scarlet aurora
#

so how would I do this

#

@fading marlin

fading marlin
#

check if payload.user_id is equal to the ID of the bot

scarlet aurora
#

ok

#

@fading marlin py if payload.user_id == '1002921149795143680':

#

like this?

fading marlin
#

user_id is an integer, and you're comparing it to a string

scarlet aurora
#

omg I'm so dumb

slate swan
#

How is it i print a value to a string? Like it takes a value and sendes it in a discord server

silk ice
#

how do you know where you want to send it?

slate swan
#

With a discord webhook

silk ice
#

ah ok

#

!d discord.SyncWebhook

unkempt canyonBOT
#

class discord.SyncWebhook```
Represents a synchronous Discord webhook.

For an asynchronous counterpart, see [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook "discord.Webhook").

x == y Checks if two webhooks are equal.

x != y Checks if two webhooks are not equal.

hash(x) Returns the webhooksโ€™s hash.

Changed in version 1.4: Webhooks are now comparable and hashable.
silk ice
#

can probably just use this then

slate swan
#

Ok thx

silk ice
#

use the send method on that and just pass the value you want printing

slate swan
#

Ok thanks you ill try

#

I almost know nothing about Python but i Will figure it out

silk ice
#

to construct one use the from_url classmethod

limpid spoke
unkempt canyonBOT
#

class discord.Webhook```
Represents an asynchronous Discord webhook.

Webhooks are a form to send messages to channels in Discord without a bot user or authentication.

There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.webhooks "discord.Guild.webhooks"), [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.webhooks "discord.TextChannel.webhooks"), [`VoiceChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.webhooks "discord.VoiceChannel.webhooks") and [`ForumChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ForumChannel.webhooks "discord.ForumChannel.webhooks"). The ones received by the library will automatically be bound using the libraryโ€™s internal HTTP session.

The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.from_url "discord.Webhook.from_url") or [`partial()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.partial "discord.Webhook.partial") classmethods.

For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html "(in aiohttp v3.8)"):
limpid spoke
#

Don't use SyncWebhook please ๐Ÿ™

spiral crypt
#
reaction = next((r for r in message.reactions if r.emoji == '๐ŸŽ‰'), None)
    if reaction:
        users = list(await reaction.users())
        if len(users) > 0:
            winner = random.choice([user for user in users if not user.bot])
            embed.add_field(name='Winner', value=winner.mention)
            await message.edit(embed=embed)
        else:
            await ctx.send("No one reacted to the giveaway.")
    else:
        await ctx.send("No one reacted to the giveaway.")

Heyo for some reason its not detecting that I reacted to the message, any idea?

scarlet aurora
#

how get unicode of an emoji

slate swan
#

back slash it in chat

slate swan
slate swan
#

then press enter

spiral crypt
#
reaction = message.reactions()
    users = [user async for user in reaction.users()]
    winner = random.choice(users)
    embed.add_field(name='Winner', value=winner.mention)
    await message.edit(embed=embed)

yeah then i updated it to this and still nothing

slate swan
#

can you show full code?

spiral crypt
#
async def create_giveaway(ctx, title: str, duration: str, *, description: str):
    duration_dict = {"s": 1, "m": 60, "h": 3600, "d": 86400}
    match = re.match(r"(\d+)([a-zA-Z]+)", duration)
    if match:
        duration_num = int(match.group(1))
        duration_unit = match.group(2).lower()
        duration_seconds = duration_num * duration_dict.get(duration_unit, 1)
    else:
        duration_seconds = int(duration)
    end_time = datetime.datetime.now() + datetime.timedelta(seconds=duration_seconds)
    if duration_seconds < 60:
        duration_string = f'{duration_seconds} seconds'
    elif duration_seconds < 3600:
        duration_string = f'{duration_seconds // 60} minutes'
    elif duration_seconds < 86400:
        duration_string = f'{duration_seconds // 3600} hours'
    else:
        duration_string = f'{duration_seconds // 86400} days'
    embed = discord.Embed(title=title, description=description)
    embed.add_field(name='Duration', value=duration_string)
    embed.add_field(name='Ends at', value=end_time.strftime("%Y-%m-%d %H:%M:%S"))
    message = await ctx.send(embed=embed)
    await message.add_reaction('๐ŸŽ‰')

    while True:
        now = datetime.datetime.now()
        remaining_time = end_time - now
        if remaining_time.total_seconds() <= 0:
            break
        if remaining_time.total_seconds() < 60:
            duration_string = f'{remaining_time.total_seconds():.0f} seconds'
        elif remaining_time.total_seconds() < 3600:
            duration_string = f'{remaining_time.total_seconds() // 60:.0f} minutes'
        elif remaining_time.total_seconds() < 86400:
            duration_string = f'{remaining_time.total_seconds() // 3600:.0f} hours'
        else:
            duration_string = f'{remaining_time.total_seconds() // 86400:.0f} days'

        embed.set_field_at(index=0, name="Duration", value=duration_string)
        await message.edit(embed=embed)
        await asyncio.sleep(300)
    reaction = message.reactions()
    users = [user async for user in reaction.users()]
    winner = random.choice(users)
    embed.add_field(name='Winner', value=winner.mention)
    await message.edit(embed=embed)
severe mural
#

hmmmm! wait think hard lol.

scarlet aurora
spiral crypt
#

ctx

severe mural
#

File "sk.py", line 121
await client.get_channel(x).send(embed=embed)
^
SyntaxError: invalid syntax

=====
Update, solution found fix done.

slate swan
spiral crypt
#
print("here??????")
    reaction = message.reactions()
    print("only here")
    users = [user async for user in reaction.users()]
    print("made it here")
    winner = random.choice(users)
    print("at least here")
    embed.add_field(name='Winner', value=winner.mention)
    await message.edit(embed=embed)

I did this really scuffed print section and it printed print("here??????")

#

Error: Command raised an exception: TypeError: 'list' object is not callable
This is the error message btw

slate swan
severe mural
#

Jay and Spooky solution:

spiral crypt
#

oh, i have

@client.event
async def on_command_error(ctx, error):
  await ctx.send(f'Error: {error}')

So it doesnt send the traceback into console

slate swan
#

comment that out for now

#

and then run the cmd and show full traceback

spiral crypt
#

okay itll be done in about 5 minutes

slate swan
spiral crypt
slate swan
#

okay

spiral crypt
#

yeye

slate swan
#

oh

#

thats why ur calling reactions. its a attr not a method. @spiral crypt

spiral crypt
#

hecc, now it gets to here

users = [user async for user in reaction.users]

but gives me the error
Error: Command raised an exception: AttributeError: 'list' object has no attribute 'users'

slate swan
#

because reaction is a list

#

of reactions

#

@spiral crypt

severe mural
#

@slate swan sorry question: await client.get_channel(x).send(embed=embed) there edit message channel?

#

example: client.get_channel.edit right?

terse coyote
#

How can I get an invitation by which a new user has joined? any ways?

scarlet aurora
#
if str(payload.emoji) != '\u274E' and payload.user_id != 1002921149795143680:```
#

This seems to not be working, does anyone know why?

naive briar
#

Print to see what the thing you're trying to compare first

slate swan
scarlet aurora
#

how can I see what reactions are in a message

#

like I wanna basically do py if 'unicode' in message.reactions: but message.reactions is in a diff format

severe mural
#

think.

scarlet aurora
ionic garden
#

for a discord bot view, can there only be a set list of buttons? can the buttons change dynamically?

slate swan
#

i mean technically yeah. you can edit the view with a new view

#

and for views you can use a decorator also

ionic garden
#

how would a decorator help?

ebon island
#

I don't even think I have an app.yaml to be honest with you ๐Ÿ˜‚ I didn't see that in docs, let me look again

slate swan
slate swan
ebon island
#

I see the link in the docs but it doesn't link to a file in the repo, what is the path and is in it in main?

#

I see publish.yml in github workflows but that's the only yml I've seen thus far

#

readthedocs.yml too

ionic garden
ebon island
#

but no app.yml or as they reference application.yaml

#

yeah

#

create view sets

#

you can change between them depending on the options selected

slate swan
slate swan
#

outdated

ionic garden
slate swan
#

and it means you don't have installed

slate swan
#

you would do that in the callback

ionic garden
#

is there an example? last time i checked each button needed its own function, etc.

#

i kinda need a way to create buttons on the fly

sick birch
#

You can subclass button if you'd like

#

The tictactoe example in the repo shows you how to do that

slate swan
sick birch
#

It's a lot more dynamic and closer to what you want

#

(Since tictactoe is also a game and the buttons reflect the game state)

ionic garden
sick birch
#

You're probably just looking to subclass Button

sick birch
#

You can change anything in the view really

ionic garden
#

oh alr then

slate swan
#

that tictactoe is a good example for what you are looking for within that lib

slate swan
#

idk how to replace the options like python discord_slash.utils.manage_commands.create_option

#

can u help

slate swan
#

@sick birch @slate swan ^

sick birch
#

I don't use the discord_slash library sorry

slate swan
#

@sick birch what do u use

sick birch
slate swan
sick birch
#
@tree.command()
async def my_slash_command(interaction: discord.Interaction, option1, option2):
  ...
slate swan
#

?

sick birch
#

option1 and option2 are your options

sick birch
#

Probably won't work without a little initial setup

#

I'd recommend reading up on the docs and examples for that

#

My intention was just to give an example

slate swan
slate swan
#

every time i try to run a bot from discord.py i get this error can sum1 plz help

#

you either have a file named discord.py, a folder named discord or some fork/third party application using the discord namespace

#

i dont ๐Ÿง

spiral crypt
#

isnt it Intents()

#
intents = discord.Intents().all()
naive briar
#

No

spiral crypt
#

thats what I've been using and its working

naive briar
#

all is a classmethod

spiral crypt
#

I have had 0 issues

slate swan
slate swan
spiral crypt
#

ah gotcha

slate swan
slate swan
#

itsn not letting me type "thx" in this channel

#

thx*

#

great

severe mural
#
async def test():
    try:
        channel = client.get_channel(1044458591664488529)
        await channel.send(" Bumping time")
    except Exception:
        #PASS OUT Without doing anything
        pass```

No solution automatic message channel? | there code by stackoverflow
slate swan
#

what is the issue?

severe mural
#

but no received channel message

slate swan
#

you need to wait until bot is ready

severe mural
slate swan
#

are u starting the task?

severe mural
#

yes correct start task

#

is werid maybe problem.

slate swan
#

yea ur task starts as soon as u fire the bot up

#

so ur trying to get the channel before the bot is ready

severe mural
#

yes already buy no solution

#

.. hmmm

slate swan
#

im telling you you are trying to get the channel before the channel is in the bot's cache

severe mural
#

hmm

slate swan
severe mural
#

ok check

#

async def my_background_task(self):
^
IndentationError: unexpected indent

#

hmm lol.

#

fix edit

#

uhh

#

no recevied channel message

#

hmmm logs error?

severe mural
shrewd fjord
#

xd

severe mural
severe mural
#

explain automatic message send channel

#

time one min

shrewd fjord
severe mural
#

sorry confuse.

shrewd fjord
#

Ur loop func is outside cog btw

severe mural
severe mural
shrewd fjord
#

Checkinh

shrewd fjord
unkempt canyonBOT
#

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

Waits until the clientโ€™s internal cache is all ready.

Warning

Calling this inside [`setup_hook()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.setup_hook "discord.Client.setup_hook") can lead to a deadlock.
severe mural
#

Hmmm

shrewd fjord
#

Bot is not sending message?

#

How are you starting the loop?

severe mural
severe mural
shrewd fjord
severe mural
#

yeah there is

shrewd fjord
#

Seems like the loop starting before even bot fully loaded ๐Ÿ—ฟ

severe mural
#

Hmm

shrewd fjord
#

test.start()

severe mural
#

how there adD?

#

ok, moment.

#

correct?

shrewd fjord
#

Also make sure to learn english more standardly :)

shrewd fjord
severe mural
severe mural
shrewd fjord
shrewd fjord
severe mural
#

@shrewd fjord nice

severe mural
shrewd fjord
shrewd fjord
severe mural
#

Yeah ok moment...

shrewd fjord
#

Ok let me send what's happening here

  • You started the loop before the bot came online
  • so doing it on setup_hook fixes that
  • you need load the internal cache, so bot can get the channel with no problem

And these are the problems and solutions ๐Ÿ—ฟ

#

Sarth Peepo_Salute

shrewd fjord
#

Please dont

#

๐Ÿ—ฟ

severe mural
#

think... maybe down and up differents.

#

confuse lol.

shrewd fjord
#

xd

#

Leave it ๐Ÿ—ฟ

slate swan
# severe mural yeah

you can use ```py
channel = client.get_partial_messageable(channel_id, type=discord.ChannelType.text)
await channel.send("...")

shrewd fjord
#

Why using big brain ;-;

#

Solve my problem bruh

slate swan
#

im using my last brain cells, that got left after making a slash help command

shrewd fjord
#

The problem is...

#

With database ๐Ÿ˜”

slate swan
#

if it's mongodb then you're talking to wrong person

shrewd fjord
#

Slashes are not that bad-

shrewd fjord
slate swan
#

bet

shrewd fjord
#

ok so i have problem with syntax and stuff

#

Whatever, i just need to delete whole table to make changes... Anyway to avoid that? Like typing the command on console it will execute for only 1 time?

#

I can add ALTER syntax or query on code, but the prob is it doesn't detect if it ran alr or not ๐Ÿ˜”

vale wing
shrewd fjord
#

Meh

slate swan
slate swan
severe mural
#

๐Ÿฅฒ

#

ya already thanks spooky

#

and @slate swan no good okay lol.

shrewd barn
#

whats wrong with it

shrewd fjord
#

What's wrong?

shrewd barn
#

it was working awhile ago

shrewd fjord
slate swan
#

every message doesn't have a content, it will return None for messages which have only images or embeds

#

and you cannot use in on None

#

!e ```py
if "deneme" in None:
print("he")

unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: argument of type 'NoneType' is not iterable
fast geode
#
import discord

import responses


async def send_message(message, user_message, is_private):
    try:
        response = responses.handle_response(user_message)
        await message.author.send(response) if is_private else await message.channel.send(response)

    except Exception as e:
        print(e)


def run_discord_bot():
    TOKEN = 'token'
    client = discord.Client()

    @client.event
    async def on_ready():
        print(f'{client.user} is now running!')

    @client.event
    async def on_message(message):
        # Make sure bot doesn't get stuck in an infinite loop
        if message.author == client.user:
            return

        # Get data about the user
        username = str(message.author)
        user_message = str(message.content)
        channel = str(message.channel)

        # Debug printing
        print(f"{username} said: '{user_message}' ({channel})")

        # If the user message contains a '?' in front of the text, it becomes a private message
        if user_message[0] == '?':
            user_message = user_message[1:]  # [1:] Removes the '?'
            await send_message(message, user_message, is_private=True)
        else:
            await send_message(message, user_message, is_private=False)

    # Remember to run your bot with your personal TOKEN
    client.run(TOKEN)
#

help

austere prairie
fast geode
#

I get intends error about init() in client = discord.Client()

#

Code golfing enthusiast, you're a great lad, could you help me resolve my issue please?

#

It's probably something very dumb

austere prairie
#

the "fixes" are just an example of how you should create your bot/clients

fast geode
#

I meant that the code sent here is without the copied code

naive briar
fast geode
#

Where I make the bot detect words and reply

austere prairie
naive briar
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

fast geode
austere prairie
#

in your case that would be creating a similar intents object as shown and adding intents=intents when you create the client

austere prairie
# unkempt canyon

in the example here intents are passed in through intents=intents in commands.Bot(...)

#

you can do a similar thing with discord.Client(...)

austere prairie
#

this bit creates the intents in the example```py

Enable all standard intents and message content

(prefix commands generally require message content)

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

fast geode
#

discord.intents or discord.Client(intents) or importing it

#

So it's from the discord package

austere prairie
#
from discord import Intents
```yes
#
intents = discord.Intents.default()
intents.message_content = True
```this also works if you don't want to import `Intents` separately
fast geode
#

Maaaan

#

I'm too dumb for that shit

#

can we VC about it?

austere prairie
#

sorry no

fast geode
#

my brain's cache is overflowing with intents

austere prairie
#

just know you have to pass them in when you create discord.Client() and the like

austere prairie
fast geode
#

same error

#

but on line 19 instead of 18 when I added that

austere prairie
fast geode
#

Im currently using chatgpt and it's very helpful

#

made it run

#

After debuging with it I just told it to make a bot.py file based on what I want it to do from what it knows from my already existing bot.py and it did just that

austere prairie
naive briar
#

Not again

slate swan
fast geode
fast geode
#

and it did just that, it had several errors, but I just told it the errors

austere prairie
#

there are better tools for that

#

eg copilot

naive briar
#

ChatGPT's knowledge is cut off after 2021, so it doesn't know that intents are required now

fast geode
#

and its a VS extention

austere prairie
#

you can get it for free if you're a student

fast geode
#

I said the version and the date of release

naive briar
fast geode
#

and it told me that it's most likely a change in the package causing it or (something else I forgot) but it doesnt know

pastel basin
fast geode
#

cant wait for ChatGPT4 lol, it should be able to make an entire website without a problem

pastel basin
#

its code is wrong most of the time

#

i have to debug it everytime

fast geode
#

not that the current one cant, but it uses some outdated packages

pastel basin
slate swan
#

It will make frontend (basic one) at most

#

It won't do backend ect

austere prairie
#

don't write code with chatGPT

slate swan
#

Chat gpt is too slept on

fast geode
# slate swan Not true

not entirely by itself, but it made me a website about cats when I asked it and also can code in sass to make fancy animations lol

pastel basin
#

its overrated too

fast geode
#

ye, maybe

#

but its very useful

slate swan
pastel basin
pastel basin
fast geode
#

for me at least, its more helpful than asking someone else lol

#

because I can just copy my code and say "I get his error, make it work"

#

and it does

pastel basin
#

i dont like to copy paste

naive briar
#

Anyways, it's getting off-topic yert

unkempt canyonBOT
pastel basin
fast geode
#

also, I just placed the text from changelog about discord packages 2.1 and about what intents are from another updated recently thread and told it to adjust my code based on the way the other codes are and it actually worked

austere prairie
#

do whatever you want, but don't complain when it can't do whatever you tell it to do

fast geode
#

Dont be like the web developers that hated copilot when it first released, please

#

(reddit threats)

austere prairie
#

sometimes it will try to fix an error, fail, and give you a paragraph bsing about how it supposedly fixed the error

austere prairie
fast geode
#

ye, it did that the first time before I mentioned the dates of changelogs. You gotta tell it when its wrong instead of trying to fix an issue that's just change how it works in newer versions

#

and even then, based on what text you give it, it can redact your code to it if you supply it with changelogs

austere prairie
#

we should move to ot

fast geode
#

off topic?

austere prairie
#

yes

fast geode
#

but that's still about how it helped me fix my python code

austere prairie
#

this channel is about discord bots

#

not chatgpt fixing python code

fast geode
#

discord bot that uses python code

#

that reminds me, now i gotta use time and date with my bot

#

Should I make it so it remembers when a message is sent or do I make it save the current time and date when its asked to execute a command that requires it to do so?

#

and does it matter from where i save the current time and date?

austere prairie
#

what are you trying to make?

fast geode
#

"I apologize for the confusion, here's an example of how your main.py, bot.py, and responses.py could be set up using the latest version of discord.py (2.1) and the features it provides. is the log from chatGPT(and the code afterwards provided) that made my bot work

fast geode
#

and keep the dates of certain information that we supply to it (we need the dates and how long the prosses takes)

austere prairie
#

I meant, what are you trying to make that involves storing time/date

fast geode
#

and he's making a script that we can have on both PCs that automatically say the bot commands and then save the reply in a notepad (on both PCs)

fast geode
potent spear
#

๐Ÿคฆโ€โ™‚๏ธ

fast geode
#

And we need it to be a discord bot

austere prairie
fast geode
#

no

#

we are having a start and end commands

#

it saves the time from -start to -end commands and when you've said them

#

and then we need a way to store them in a txt file and to filter that

#

and it also saves other irelevant information among the dates.

#

its kinda like the chatlogs, but not exactly

#

like I said, its just for my server

austere prairie
fast geode
#

ty

upbeat otter
fast geode
#

He already has a scripts made that works with discord bot commands and then saves the bot replies

upbeat otter
#

he who

fast geode
#

it automatically times the command and saves the reply, we tested it on song requests and it works, it also has a small UI where we type the command we want to run

fast geode
upbeat otter
#

๐Ÿ’€ oh ok

static holly
#

hello, I would like to be able to have the choice to add a @mention in my command with a condition.
1 !hi = send "hi + author mention
2 !hi @mention = author mention say "hi" to @mention

how to do this please?

timber grove
#

hello do you know any good youtube tutorials to learn how to make discord bots in python ?

paper sluice
unkempt canyonBOT
#
Noooooo!!

No documentation found for the requested symbol.

paper sluice
#

!d discord.Member.mention

unkempt canyonBOT
static holly
#

that, I already knew, I ask how to write that now?

winged coral
#

How to write what?

#

It's a property. You can string format it or just send it as is

static holly
winged coral
#

So access that property and use string formatting to plug it into your response string

#

F strings would be easiest

paper sluice
static holly
winged coral
#

Not at all

#

discord.Member is a class, you want a specific instance of that class which is being passed to your command

#

You can typehint the member arg as the discord.Member class to get the library to handle the conversion implicitly

#

You also don't need the if True check, I don't really understand why it's there at all

#

And you're using ctx.member, which isn't a thing

static holly
#

i'm a noob, sorry ^^

winged coral
#

It's okay

static holly
winged coral
#

Do you have any kind of understanding in regards to OOP (object oriented programming) in python? Classes etc

static holly
#

not really

static holly
winged coral
#

I recommend you begin to learn about some basic OOP

slate swan
#

is there an event for the server join ?

winged coral
#

d.py is HEAVILY object oriented and almost every argument your receive will be a custom class

winged coral
winged coral
unkempt canyonBOT
#

discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") joins a guild.

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

thanks

dense merlin
#
@tree.command(name='meme',description='yay a meme') #declares a slash command   
async def meme(interaction:discord.Interaction): #creates function for interaction
   await interaction.response.defer() #Defers the response, allowing upto 15 minutes to respond to the interactiob
   em = discord.Embed(title='',description='')
   async with aiohttp.ClientSession() as cs:
        async with cs.get('https://www.reddit.com/r/shitposting/new.json?sort=hot') as r:
            res = await r.json()
            x = randint(0,25)
            em.set_image(url=res['data']['children'][x]['data']['url'])
            em.set_footer(text='these memes suck')
            print(res['data']['children'][x]['data']['url'])
            await interaction.followup.send(embed=em)    

most of the time the image does not load why

#

i looked at the url and there is an image

vale wing
#

Is there an error

#

Also print the url you put into embed

#

A you already do that

#

Then give an example of that URL

static holly
#

how can i replace ctx.author.display_name by @mention? in line 4

embed=discord.Embed (title=f"Un gage pour {ctx.author.display_name}
@commands.command()
    async def gage(self, ctx,):
        r = random.choice(liste_gage)
        description_embed = r.format(mention=ctx.author.mention)
        embed=discord.Embed (title=f"Un gage pour {ctx.author.display_name}!", color=discord.Color.orange(), description = (description_embed))
        embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar.url)
        file = discord.File('images/gage_img.png')  
        embed.set_thumbnail(url="attachment://gage_img.png")
        await ctx.send(embed=embed, file=file)
static holly
upbeat otter
#

๐Ÿ’€ where's author gonna come from then

static holly
#

dont work!

upbeat otter
#

ok

#

what doesn't work

#

and don't mention in the title

static holly
upbeat otter
#

because that doesn't work

static holly
#

hmmmmm, ok

#

critical damage...

upbeat otter
static holly
#

look

#
 @commands.command()
    async def gage(self, ctx,):
        r = random.choice(liste_gage)
        description_embed = r.format(mention=ctx.author.mention)
        embed=discord.Embed (title=f"Un gage pour {ctx.author.display_name}!", color=discord.Color.orange(), description =(f"{ctx.author.mention}, {description_embed}"))
        embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar.url)
        file = discord.File('images/gage_img.png')  
        embed.set_thumbnail(url="attachment://gage_img.png")
        await ctx.send(embed=embed, file=file)
#

ctx.author.mention = !gage @mention, no?

slate swan
#

is there a way to check if a user has a early supporter badge or not

vale wing
vale wing
unkempt canyonBOT
autumn totem
#

Can somebody tell me why my code isnt working? When I do !verify nothing happens?

import discord
from discord.ext import commands

client = commands.Bot(command_prefix = "!")

@client.command()
async def verify(ctx):
    author = ctx.message.author
    role = discord.utils.get(ctx.guild.roles, name="Verified")
    await author.add_roles(role)
    await ctx.send(f"{author.mention} has been verified and given the {role.name} role.")

client.run("-")

slate swan
#

user_channels = {}

@bot.event
async def on_message(message):

    if message.guild is None:

        user_channel = user_channels.get(message.author.id)
        if user_channel:

            await bot.get_channel(user_channel).send(f"{message.author.mention} said: {message.content}")
        else:

            guild = bot.get_guild(1063208577130582016)

            user_channel = await guild.create_text_channel(f"modmail-{message.author.name}")

            user_channels[message.author.id] = user_channel.id

            await user_channel.send(f"{message.author.mention} said: {message.content}")

why isnt this working? Its not creating a channel in the guild.

#

bot has admin, bot is in the guild

#

nvm, i got the issue.

#

whoever wants that code can have it

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.

proper plume
#

hello

spiral crypt
#
async def warn(ctx, user: discord.User, *, reason):
    warn.warn_user(ctx, user, user_warns, *reason)

def warn_user(ctx, user: discord.User, user_warns: dict, *, reason):
    user_id = str(user.id)
    if user_id not in user_warns:
        user_warns[user_id] = {}
    warns = user_warns[user_id]
    warn_number = len(warns) + 1
    warns[f"warn{warn_number}"] = reason
    saves.save_user_warns(user_warns)
    await ctx.send(f'{user.name} was warned for {reason}')

I have these two functions where warn_user is in a file called warn, but the *reason in the original async def warn gets errored out and says its an unexpected argument? Anyone know why

proper plume
#

I was writing my discord bot and i got this error:

#

can anyone help me pls

#

i writing it on replit

spiral crypt
#

it says to enable your priveleged intents in the developer portal

proper plume
#

k

#

ima gona try it

#

YEY ty so much

#

and 1 more question

#

i got problem with it

ionic garden
#

well, i guess there isn't the object AsyncWebhookAdapter in discord

proper plume
#

and do you know where it is

#

?

cold sonnet
#

cuz ur hungarian Imma give you an advice that's gonna last you for the rest of your life

proper plume
#

ok

#

kรถsz tesรณ

cold sonnet
#

type AsyncWebhookAdapter in the search bar

#

and it's gonna show you where the object is

#

szรญvesen tesรณ

slate swan
unkempt canyonBOT
#

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

proper plume
#

why did a break the laws?

cold sonnet
slate swan
#

"Lightening nuke bot" doesn't sound very appropriate in this server

ionic garden
#

nuke bot? sounds sus

slate swan
#

Read dir

#

In image it shows nuke bot

proper plume
#

oh, ye I tried to do it, but i changed the commands, and now the name is only nuke bot

cold sonnet
proper plume
#

its the file name and Im too bored to change it

cold sonnet
#

I'm on phone I didn't check

slate swan
#

user_channels = {}

first_dmed_user = None

@bot.event
async def on_message(message):
    global first_dmed_user
    user_channel = user_channels.get(message.author.id)

    if message.guild is None:

        if first_dmed_user is None:
            first_dmed_user = message.author
        if user_channel:

            if message.channel.id in user_channels.values():

                await first_dmed_user.send(f"You said in {message.channel.mention}: {message.content}")
            else:

                await bot.get_channel(user_channel).send(f"{message.author.mention} said: {message.content}")
        else:

            guild = bot.get_guild(1063208577130582016)

            user_channel = await guild.create_text_channel(f"modmail-{message.author.name}")
            await user_channel.set_permissions(message.author, read_messages=False)
            await user_channel.set_permissions(guild.default_role, read_messages=False)
            category_id = 1066437408582815754 
            category = bot.get_channel(category_id)
            await user_channel.edit(category=category)

            # Store the channel ID in the dictionary
            user_channels[message.author.id] = user_channel.id
            # Send the message to the user's channel
            await user_channel.send(f"{message.author.mention} said: {message.content}")
#
@bot.event
async def on_ready():
    @bot.event
    async def on_message(message):
        if message.channel.id in user_channels.values():
            await first_dmed_user.send(f"{message.author.mention} said in {message.channel.mention}: {message.content}")```
sick birch
#

Why are you nesting the on_message?

slate swan
#

Anyone know why this isnt working?

sick birch
#

Also FYI you can only one one @client.event for each event

#

So the 2nd on_message will override the first one

cold sonnet
slate swan
#

so i should remove one?

spiral crypt
#

oh? are you not able to do 2 on_message() events?

slate swan
#

ig not

spiral crypt
#

well that sux

slate swan
#

what should i do? @sick birch

slate swan
fresh hinge
#

Is this leetcode

spiral crypt
#

I have a "@client.listen()"

sick birch
#

And remove one of your other on messages

slate swan
# spiral crypt I have a "@client.listen()"

you can have 2 event of same kind using this ```py

@bot.listen("on_message")
async def name_this_anything(msg):
...

@bot.listen("on_message")
async def name_this_anything_but_not_same_as_above(msg):
...

#

Command raised an exception: TypeError: Context.send() got an unexpected keyword argument 'components'

slate swan
#

?

#

i have a bot thats broken

#

i need it to read a discordid and give it a role from the message

#

the message author is not the person receiving the role

slate swan
#

!d discord.ext.commands.Context.send

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

Sends a message to the destination with the content given.

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

For interaction based contexts this does one of the following...
autumn totem
#

Can someone help me? I get this error line 5, in <module> intents.guild_role = True

This is the code


import discord
from discord.ext import commands

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

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

@client.command()
async def verify(ctx):
    author = ctx.message.author
    role = discord.utils.get(ctx.guild.roles, name="Verified")
    await author.add_roles(role)
    await ctx.send(f"{author.mention} has been verified and given the {role.name} role.")

client.run("-") ```
slate swan
#

can someone help me

slate swan
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

proper plume
#

hey, its me again, anyone can help me pls

slate swan
#

discord.Member.

proper plume
#

omg im so stupid

#

ty

#

ummm

#

i think i have another

#

question

#
@client.has_permissions(kick_members=True)
slate swan
#

!discord.ext.commands

#

decorators

#

!d discord.ext.commands.bot_has_permissions

unkempt canyonBOT
#

@discord.ext.commands.bot_has_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_permissions "discord.ext.commands.has_permissions") except checks if the bot itself has the permissions listed.

This check raises a special exception, [`BotMissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BotMissingPermissions "discord.ext.commands.BotMissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
slate swan
#

@proper plume

proper plume
#

tyy

slate swan
#

Decors

proper plume
#

umm do I need to import something for it?

#

or just discord

slate swan
#

you need to import it

proper plume
slate swan
#

huh?

#

no look at the docs of what i linked

#

if u dont understand how to import what i just linked i suggest learning some basics before divining into a discord bot

slate swan
#

they should make a quiz for python basics to gain access to this channel

#

Fr people in this channel are so clueless and first thing they do is make discord bot when learning python and are stuck in tutorial hell

autumn totem
#

Can someone help me with those errors? Heres the code

class Verification(discord.ui.View):
  def __init__(self):
    super().__init__(timeout = None)
  @discord.ui.button(label="Verify",custom_id = "Verify",style = discord.ButtonStyle.success)
  async def verify(self, interaction, button):
    role = -
    user = interaction.user
    if role not in [y.id for y in user.roles]:
      await user.add_roles(user.guild.get_role(role))
      await user.send("You have been verified!")

@bot.command()
async def initialize(ctx):
  embed = discord.Embed(title = "Verification", description = "Click below to verify.")
  await ctx.send(embed = embed, view = Verification())
  
bot.run(os.environ.get('-'))
tawny junco
#

Where is the error

#

All you did was sent the traceback (I think it's called) but no actual error

slate swan
#

ur token wrong

autumn totem
#

Nah I mean that the bot aint starting

slate swan
#

im pretty sure

autumn totem
#

the token will be pasted into bot.run(os.environ.get('Token'))

slate swan
#

u should probably post the entire traceback

#

not sure why u cut it off to begin with

autumn totem
#

Alright sec

#
from discord.ext import commands
import discord.ui
import os

intents = discord.Intents.all()

bot = commands.Bot(command_prefix='.', intents=intents, help_command=None)

@bot.event
async def on_ready():
  print('System rebooted.')
  bot.add_view(Verification())

class Verification(discord.ui.View):
  def __init__(self):
    super().__init__(timeout = None)
  @discord.ui.button(label="Verify",custom_id = "Verify",style = discord.ButtonStyle.success)
  async def verify(self, interaction, button):
    role = -
    user = interaction.user
    if role not in [y.id for y in user.roles]:
      await user.add_roles(user.guild.get_role(role))
      await user.send("You have been verified!")

@bot.command()
async def initialize(ctx):
  embed = discord.Embed(title = "Verification", description = "Click below to verify.")
  await ctx.send(embed = embed, view = Verification())
  
bot.run(os.environ.get('-'))```
slate swan
#

can't tell why the bot won't start with what u provided

#

traceback the error log

#

not ur code

autumn totem
#
Traceback (most recent call last):
  File "c:\Users\kamil\Desktop\Python\Worthy-Bot\main.py", line 31, in <module>
    bot.run(os.environ.get("TOKEN"))
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 716, in run
    return future.result()
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 695, in runner
    await self.start(*args, **kwargs)
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 658, in start
    await self.login(token)
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 508, in login
    raise TypeError(
TypeError: token must be of type str, not NoneType ```
slate swan
#

yeah ur not supplying a token

autumn totem
#

Lmao I know that I need to put the token where it says TOKEN

tawny junco
#

You need to import dotenv

autumn totem
#

dont get me wrong haha

tawny junco
#
from dotenv import load_dotenv

load_dotenv()
#

Do this

#

And it should work

autumn totem
#
Collecting dotenv
  Using cached dotenv-0.0.5.tar.gz (2.4 kB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error

  ร— python setup.py egg_info did not run successfully.
  โ”‚ exit code: 1


tawny junco
#

You have to pip install python-dotenv

autumn totem
#

Ah ok

tawny junco
#

python-dotenv

autumn totem
#

thanks I wrote pip install dotenv

tawny junco
#

Yeah I figured

autumn totem
#
line 1
    .all()
    ^
SyntaxError: invalid syntax
#

Now i get this

#

Idk why it says line 1 but .all is in line 9

tawny junco
#

Save your file and run it again

#

It should atleast update the error

autumn totem
#
Traceback (most recent call last):
  File "c:\Users\kamil\Desktop\Python\Worthy-Bot\main.py", line 34, in <module>
    bot.run(os.environ.get("TOKEN"))
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 716, in run
    return future.result()
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 695, in runner
    await self.start(*args, **kwargs)
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 658, in start
    await self.login(token)
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 508, in login
    raise TypeError(
TypeError: token must be of type str, not NoneType

#

Now theres thesee errors

tawny junco
#

You did create a .env file right?

autumn totem
#

No actually not

#

sorry its my first time coding a bot haha

tawny junco
#

Do that in the same directory

autumn totem
#

does it have to have a specific name?

#

ok done

tawny junco
#

Just name it

.env
autumn totem
#

done

tawny junco
#

Now create your key and paste your token

#
TOKEN=fhdjjkdgfbh.sdjdgljdscnj
autumn totem
#

done

tawny junco
#

Save the file and run the code again

autumn totem
#
Traceback (most recent call last):
  File "c:\Users\kamil\Desktop\Python\Worthy-Bot\main.py", line 34, in <module>
    bot.run(os.environ.get("TOKEN"))
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 716, in run
    return future.result()
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 695, in runner
    await self.start(*args, **kwargs)
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 658, in start
    await self.login(token)
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 508, in login
    raise TypeError(
TypeError: token must be of type str, not NoneType

tawny junco
autumn totem
#

I did

tawny junco
#

Did you create the .env file in the same folder as your py file?

autumn totem
tawny junco
#

What is the name of the key

#

The word before the equal sign

autumn totem
#

TOKEN?

#

you mean that?

tawny junco
#

Yes

autumn totem
#

so you want the token?

tawny junco
#

No

#

Don't send the token

autumn totem
#

yea I wont

tawny junco
#

Did you do

os.environ.get("TOKEN")
#

?

autumn totem
#

ahh yes

tawny junco
#

Replace that "-" with "TOKEN"

autumn totem
#
Traceback (most recent call last):
  File "c:\Users\kamil\Desktop\Python\Worthy-Bot\main.py", line 34, in <module>
    bot.run(os.environ.get("TOKEN"))
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 716, in run
    return future.result()
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 695, in runner
    await self.start(*args, **kwargs)
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 659, in start
    await self.connect(reconnect=reconnect)
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 598, in connect
    raise PrivilegedIntentsRequired(exc.shard_id) from None
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.
tawny junco
#

Run it now

autumn totem
#

I got this error

tawny junco
#

You need to head over to the developer portal and enable privileged intents

autumn totem
#

and now I need to try again?

tawny junco
#

Yes

autumn totem
#

broooooo

#

It worked

#

THANKS ALOT โค๏ธ

tawny junco
#

Gj

autumn totem
#

Yo bro

#

Now I got another problem lol

#
Ignoring exception in view <Verification timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Verify' emoji=None row=None>:
Traceback (most recent call last):
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\kamil\Desktop\Python\Worthy-Bot\main.py", line 24, in verify
    user = interaction.user
AttributeError: 'Button' object has no attribute 'user'
Ignoring exception in view <Verification timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Verify' emoji=None row=None>:
Traceback (most recent call last):
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\kamil\Desktop\Python\Worthy-Bot\main.py", line 24, in verify
    user = interaction.user
AttributeError: 'Button' object has no attribute 'user'
#

this is the error

sick birch
slate swan
#

looks like u typehinted interaction to a button?

autumn totem
#
import discord
from discord.ext import commands
import discord.ui
import os
from dotenv import load_dotenv

load_dotenv()

intents = discord.Intents.all()

bot = commands.Bot(command_prefix='.', intents=intents, help_command=None)

@bot.event
async def on_ready():
  print('System rebooted.')
  bot.add_view(Verification())

class Verification(discord.ui.View):
  def __init__(self):
    super().__init__(timeout = None)
  @discord.ui.button(label="Verify",custom_id = "Verify",style = discord.ButtonStyle.success)
  async def verify(self, interaction, button):
    role = 1061850690110111774
    user = interaction.user
    if role not in [y.id for y in user.roles]:
      await user.add_roles(user.guild.get_role(role))
      await user.send("You have been verified!")

@bot.command()
async def initialize(ctx):
  embed = discord.Embed(title = "Verification", description = "Click below to verify.")
  await ctx.send(embed = embed, view = Verification())
  
bot.run(os.environ.get("TOKEN"))
sick birch
#

If I'm to guess you probably fipped the order of the arguments

slate swan
#

^

#

wait but docs show inter, button lol

vestal dagger
slate swan
autumn totem
#

Where can I find the docs?

autumn totem
#

thanks

#

Soo what do I need to do to fix this?

#

This is my first time doing a discord bot in python

slate swan
#

try to swap interaction and button

autumn totem
#

like this?

#

nah bro its still failing

slate swan
#

whats the error show?

autumn totem
#
Ignoring exception in view <Verification timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='\u2705' emoji=None row=None>:
Traceback (most recent call last):
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\kamil\Desktop\Python\Worthy-Bot\main.py", line 26, in verify
    await user.add_roles(user.guild.get_role(role))
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\member.py", line 1007, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'
slate swan
#

y.id is none existent

#

if not any(role == _role .id for _role in user.roles)

#

@autumn totem

autumn totem
#

Ok so where should I paste this?

#

ah wait

#

like this?

#

there is still a error

slate swan
#

logs

autumn totem
#
 File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\kamil\Desktop\Python\Worthy-Bot\main.py", line 26, in verify
    await user.add_roles(user.guild.get_role(role))
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\member.py", line 1007, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'
Ignoring exception in view <Verification timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='\u2705' emoji=None row=None>:
Traceback (most recent call last):
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\kamil\Desktop\Python\Worthy-Bot\main.py", line 26, in verify
    await user.add_roles(user.guild.get_role(role))
  File "C:\Users\kamil\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\member.py", line 1007, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'


slate swan
#

what are u intents?

#

nvm u have all

autumn totem
#

yh

slate swan
#

does the role actually exist? make sure ur id is correct

#

cause i dont think it is

rapid knoll
#

how do I create timed events so that a command is run by the bot every 10 minutes

slate swan
autumn totem
#

it was wrong thanks alot bro

slate swan
#

yup np

rapid knoll
autumn totem
#

How do I add a paragraph between this 2 sentences?

young dagger
#

Is there any other way to do this?

    duration_minutes = duration_seconds / 60
    duration_hours = duration_minutes / 60
    duration_days = duration_hours / 24
    duration_weeks = duration_days / 7

    if duration_seconds < 60:
        if duration_seconds == 1:
            duration_string = "1 second"
        else:
            duration_string = f"{duration_seconds} seconds"
    elif duration_seconds < 3600:
        if duration_minutes == 1:
            duration_string = "1 minute"
        else:
            duration_string = f"{duration_minutes:.2f} minutes"
    elif duration_seconds < 86400:
        if duration_hours == 1:
            duration_string = "1 hour"
        else:
            duration_string = f"{duration_hours:.2f} hours"
    elif duration_seconds < 604800:
        if duration_days == 1:
            duration_string = "1 day"
        else:
            duration_string = f"{duration_days:.2f} days"
    else:
        if duration_weeks == 1:
            duration_string = "1 week"
        else:
            duration_string = f"{duration_weeks:.2f} weeks"```
sick birch
#

It'll convert for you

young dagger
sick birch
tired notch
#

is there a way to create my own function decorator that can check if a given id exists in a command?

sick birch
#

Or ("s" if duration_seconds > 1 else "") if that suits your fancy more

tired notch
#

ah much thanks

#

is there a way to pass anything other than ctx?

scarlet aurora
#

how do I check how many times a reaction is made in a message

tired notch
#

i think the reaction object has a .count

cloud dawn
unkempt canyonBOT
paper crescent
#

Hello! Can you help me? I wrote a discord giveaway bot and it doesn't work.

cloud dawn
#

You also need the reactions intent.

paper crescent
cloud dawn
#

"messsage"

paper crescent
#

so what instead of it

cloud dawn
#

Well "message" you used 3 s's

paper crescent
#

oh

young dagger
sick birch
#

Shouldn't really matter if it's user-facing

young dagger
sick birch
#

I mean, it really doesn't matter

#

Just pick one and roll with it
But stay consistent

paper crescent
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'async_generator' object has no attribute 'flatten'

paper crescent
#

i didn't know that one and it isn't working that i copied ๐Ÿ˜„
users = await new_msg.reactions[0].users().flatten()

#

what do I need to change this to

cloud dawn
#

Remove flatten

young dagger
sick birch
#

If by "parse" you mean just plugging it into timedelta, yes

young dagger
sick birch
#

yes you will still have to parse that out

tired notch
#

for some reason my discord.py program doesn't have runtime exceptions? there is nothing in the console when a runtime error happens

#

or am i just on something

sick birch
tired notch
#

i have some but not for the ones that arent showing

#

like if i try adding a string to an int theres no error the bot just says application failed to respond or something

sick birch
#

People usually do those wrong

tired notch
#
    async def on_command_error(self, ctx, error):
        if isinstance(error, commands.errors.CommandOnCooldown):
            embed = discord.Embed(title="Error",
                                  description="You have already used this command. You can use it again in " + seconds_to_time(
                                      error.retry_after) + ".", color=discord.Color.red(),
                                  timestamp=datetime.datetime.now() + datetime.timedelta(seconds=error.retry_after))
            embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar)
            await ctx.send(embed=embed)
        if isinstance(error, commands.MissingRole):
            embed = discord.Embed(title="Error", description="You do not have the roles to use this command.", color=discord.Color.red())
            embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar)
            await ctx.send(embed=embed)```
#

nvm just read the docs

paper crescent
#

TypeError: object of type 'async_generator' has no len()

naive briar
#

Read the error

#

That's your answer

paper crescent
#

mhm and how to pick someone from all users that reacted to a message?

slate swan
#

!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 "(in Python v3.11)") 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 "discord.abc.Snowflake") abc.

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

Examples

Usage...
slate swan
#

!d random.choice

unkempt canyonBOT
#

random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
slate swan
young dagger
# sick birch yes you will still have to parse that out

Like this?

if infraction['duration'] is not None:
    duration_seconds = infraction['duration']
    duration = datetime.timedelta(seconds=duration_seconds)
    if duration.days > 0:
        if duration.days == 1:
            duration_str = f"{duration.days} day"
        else:
            duration_str = f"{duration.days} days"
    elif duration.seconds > 3600:
        hours = duration.seconds // 3600
        if hours == 1:
            duration_str = f"{hours} hour"
        else:
            duration_str = f"{hours} hours"
    elif duration.seconds > 60:
        minutes = duration.seconds // 60
        if minutes == 1:
            duration_str = f"{minutes} minute"
        else:
            duration_str = f"{minutes} minutes"
    else:
        seconds = duration.seconds
        if seconds == 1:
            duration_str = f"{seconds} second"
        else:
            duration_str = f"{seconds} seconds"
    infraction["duration"] = duration_str
else:
    infraction["duration"] = "Indefinite"```
sick birch
#

Looks about right

young dagger
sick birch
#

Elaborate on what you mean by "doesn't work"

young dagger
#

For some reason its having problems with converting when its a number

#

In this case, '1800'

sick birch
#

What sort of problems?

young dagger
#

idk you tell me ๐Ÿ˜”

#

If I remove the converter it work

sick birch
#

Details, tracebacks, code, expected behaviour vs actual behaviour would all be great

young dagger
# sick birch Details, tracebacks, code, expected behaviour vs actual behaviour would all be g...

It won't post the embed:

            # Add a field for each infraction
            infraction_string = ""

                if infraction['type'] in ["Ban", "Mute"]:
                    if infraction['duration'] == "None":
                        infraction["duration"] = "Indefinite"
                    else:
                        duration_seconds = int(infraction['duration']) if infraction['duration'] != "None" else None
                        if duration_seconds is not None:
                            datetime.timedelta(minutes=duration_seconds)
                            minutes = duration.seconds // 60
                            if minutes == 1:
                                duration_str = f"{minutes} minute"
                            elif minutes > 1:
                                duration_str = f"{minutes} minutes"
                            infraction["duration"] = duration_str
                    field_value = f"**Duration:** {infraction['duration']}\n**Reason:** {infraction['reason']}"
                else:
                    field_value = f"**Reason:** {infraction['reason']}"
                infraction_string += field_value + "\n\n"

            # Create an embed object for the modlogs message
            description = f"{member.mention}"
            embed = discord.Embed(title=f"{member.name}#{member.discriminator}'s Logs", description=description, color=discord.Color.orange())

            # Send the embed message
            await ctx.send(embed=embed)```
sick birch
#

Agh that's a lot of nesting

#

Any tracebacks in console?

young dagger
#

No

sick birch
#

Error handlers?

young dagger
sick birch
#

!pastebin the whole thing please

unkempt canyonBOT
#

Pasting large amounts of code

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

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

slate swan
#

can

#

someone help me

sour ember
#

Hi. How do I get my Discord bot to connect to a voice channel?

slate swan
#

when trying to get the guild of a server from an interaction it gives me this: <member 'guild_id' of 'Interaction' objects>
This is my code: py await interaction.response.send_message(discord.Interaction.guild_id)

slate swan
#

you are also using discord.Interaction which is a class.

#

you need to do interaction.guild_id

austere prairie
#

But getting it to speak is a different story

slate swan
#

im pretty sure it's .connect

#

!d discord.VoiceProtocol.connect

unkempt canyonBOT
#

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

An abstract method called when the client initiates the connection request.

When a connection is requested initially, the library calls the constructor under `__init__` and then calls [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol.connect "discord.VoiceProtocol.connect"). If [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol.connect "discord.VoiceProtocol.connect") fails at some point then [`disconnect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol.disconnect "discord.VoiceProtocol.disconnect") is called.

Within this method, to start the voice connection flow it is recommended to use [`Guild.change_voice_state()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.change_voice_state "discord.Guild.change_voice_state") to start the flow. After which, [`on_voice_server_update()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol.on_voice_server_update "discord.VoiceProtocol.on_voice_server_update") and [`on_voice_state_update()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_voice_state_update "discord.on_voice_state_update") will be called. The order that these two are called is unspecified.
austere prairie
#

^

sour ember
#

And how can I make the bot share screen and play a video?

slate swan
#

no can do

sour ember
#

Yes you can, I know a bot that shares screen and shows youtube videos

slate swan
#

then they are selfbotting and that is against discord tos

sour ember
#

Is there a way for a bot to show live streams?

rare echo
sour ember
#

Is there a way for a bot to show live streams in a chat or voice channel?

rare echo
#

once again, a bot account canโ€™t do that, so no

#

your only bet is sending a link in chat

tawdry swallow
#

Anyone knows a simple but reliable way to load a cog using discord.py?

rare echo
#

thatโ€™s about as far as you can get for video

tawdry swallow
#

eh

hushed galleon
#

reliable? whats wrong with the load_extension/add_cog mechanism?

tawdry swallow
#

I tried it but the whole cog thingy broke down so I just deleted the whole previous code and am restarting from scratch again

slate swan
#

are there really no docs on it ?

tawdry swallow
#

there are but im too dumb too understand lol

slate swan
#

i mean like examples

#

i cant find any in the repo

hushed galleon
#

yeah its quite weird that dpy doesnt have an example of combining cogs and extensions

tawdry swallow
#

Interesting

slate swan
#

aren't they similiar to disnake tho just

def setup(bot):
    bot.add_cog(ButtonEvent(bot))

then the load_extensions()

hushed galleon
slate swan
#

oh there is an example. why tf is it nested in change logs lmao

hushed galleon
#

ehh it doesnt describe the use of cogs and extensions

slate swan
#

yeah but at least it's something lol

tawdry swallow
#

Indeed

hushed galleon
# tawdry swallow I tried it but the whole cog thingy broke down so I just deleted the whole previ...

a typical structure would be each cog in its own file (or package) along with a setup function (making it an "extension"), and then a setup_hook or similar that loads the extension when your bot starts, e.g. ```py

cogs/stuff.py

class Stuff(commands.Cog):
...

async def setup(bot):
await bot.add_cog(Stuff(...))```

# main.py
class MyBot(commands.Bot):
    async def setup_hook(self):
        await self.load_extension("cogs.stuff")```
tawdry swallow
#

very interesting

slate swan
tawdry swallow
#

The code works but when I try to run a command it gives me thsi error in the terminal :
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found

#

but the command is present in the cog

vale wing
#

I make autosetup, screw doing add_cog for each cog, too wet code

tawdry swallow
#

Interesting

vale wing
#

I married inspect

tawdry swallow
#

Very interesting

vale wing
tawdry swallow
#

the cog :D

vale wing
#

Seems legit, how do you load extension?

#

Legit except naming convention, classes follow PascalCase

tawdry swallow
#

Oh wait

vale wing
#

Or UpperCamelCase those are same things

tawdry swallow
#

there was a indentation error lol

vale wing
#

Unrelated

tawdry swallow
vale wing
#

Ye there's an issue

tawdry swallow
#

Interesting

vale wing
#

You need to subclass the bot like this

class Bot(commands.Bot):
    async def setup_hook(self):
        ...

bot = Bot(...)```
#

Not the way you did

#

And yeah better name variable bot instead of client

tawdry swallow
#

I like it as client :D

#

but imma change it to bot

slate swan
#

messages = {}

@bot.event
async def on_message(message):
    if message.author.bot:
        return

 
    user_messages = messages.get(message.author.id, [])

    user_messages.append(message.content)

    user_messages = user_messages[-5:]
    messages[message.author.id] = user_messages


    if user_messages.count(message.content) > 1:
        await message.delete()
        await message.channel.send("This message was deleted for being a duplicate.")``` Why isnt this code working?
tawdry swallow
vale wing
tawdry swallow
#

*Simpler terms *pBear

vale wing
#

Doesn't it

tawdry swallow
#

Interesting

vale wing
#

And btw for logs you better use some logger

#

!pypi exencolorlogs like mine

unkempt canyonBOT
vale wing
#

I need to document it

tawdry swallow
#

So this should be the same like this?:

vale wing
#

Your cogs is a list

#

You need to iterate and add each element

tawdry swallow
#

Interesting

#

well I removed the cog var and just put the name of the cog but it still isn't working '-'

naive briar
#

it's not working doesn't help

tawdry swallow
vale wing
#
EXTENSIONS = ("fun",)

class MyBot(commands.Bot):
    async def setup_hook(self):
        for ext in EXTENSIONS:
            await self.load_extension(ext)

    async def on_ready(self):
        print("Ready")


bot = MyBot(...)
bot.run(...)```
Very spoonfeeding @tawdry swallow
tawdry swallow
#

Ye Very Spoonfeeding lol

fossil talon
#
@bot.command(pass_context=True)
@commands.has_permissions(administrator=True)
async def clean(ctx, limit: int):
        await ctx.channel.purge(limit=limit)
        await ctx.send('Cleared by {}'.format(ctx.author.mention))
        await ctx.message.delete()

@clean.error
async def clear_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You cant do that!")

discord.ext.commands.errors.CommandNotFound: Command "purge" is not found
#

why

slate swan
#

bro ur cmd is literally named clean

fossil talon
#

wym

#

its a purge command

slate swan
#

and what does your error say?

fossil talon
#

discord.ext.commands.errors.CommandNotFound: Command "purge" is not found

#

am i not using discord rewrite?

slate swan
#

and what cmd did u just so

fossil talon
#

#clean

slate swan
#

ur copy pasting

#

there is no way

fossil talon
#

wdym

slate swan
#

you do not have a command named purge

naive briar
#

Ridiculous

fossil talon
#

oh

#

i found the issue

slate swan
#

yea

fossil talon
#

very little sleep past few days

slate swan
#

same

fossil talon
#

how do i handle a timeout error in a wait_for

naive briar
#

Normally

slate swan
unkempt canyonBOT
#

exception asyncio.TimeoutError```
A deprecated alias of [`TimeoutError`](https://docs.python.org/3/library/exceptions.html#TimeoutError "TimeoutError"), raised when the operation has exceeded the given deadline.

Changed in version 3.11: This class was made an alias of [`TimeoutError`](https://docs.python.org/3/library/exceptions.html#TimeoutError "TimeoutError").
fossil talon
#

much love my friend

upbeat otter
slate swan
#

mentions in embed is crinj, just use the repr of User

slate swan
#

How can I see someone's status after it updates?

#

on_presence_update

#

parameters being before, after?

#

yea

#

!d discord.on_presence_update

unkempt canyonBOT
#

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

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

โ€ข status

โ€ข activity

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

or how can I target a certain update

#

!d discord.Member.activities

unkempt canyonBOT
#

The activities that the user is currently doing.

Note

Due to a Discord API limitation, a userโ€™s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.

slate swan
#

just read docs youll find all your answers

#

alright

white citrus
#
future: <Task finished name='discord-ui-view-timeout-05636a1ce2879fee8549ffc73c7f17ad' coro=<HelpView_Slash.on_timeout() done, defined at c:\Discord\Maja Projekt\MajaSystem_Test\modules\helpV2\cog.py:62> exception=AttributeError("'str' object has no attribute 'response'")>
Traceback (most recent call last):
  File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\helpV2\cog.py", line 65, in on_timeout
    await self._help_command.response.edit(view=self)
AttributeError: 'str' object has no attribute 'response'```
#
class HelpView_Slash(nextcord.ui.View):
    def __init__(self, ctx, help_command: "MyHelpCommand_Slash", options: list[nextcord.SelectOption], *, timeout: Optional[float] = 180):
        super().__init__(timeout=timeout)
        self._help_command = help_command
        self.ctx = ctx
        self.add_item(HelpDropdown_Slash(self.ctx, help_command, options))
        
    async def on_timeout(self):
        # remove dropdown from message on timeout
        self.clear_items()
        await self._help_command.response.edit(view=self)```
slate swan
#

wtf

white citrus
slate swan
#
@bot.event
async def on_presence_update(before, after):
    print(f"{after} + {before.status}")
    print(f"{after} + {after.status}")```
#

Output when changing my status from online to dnd

cyt#0001 + online
cyt#0001 + dnd
cyt#0001 + online
cyt#0001 + dnd```
#

Why is it doing it twice

slate swan
white citrus
slate swan
#

u wrote all of that? there is no way

#

you realize help_command is a string right ?

white citrus
#

Now yes

#

So how can i edit the message

slate swan
#

yea theyll just need to get orig

#

bruh

#

im slow af

white citrus
#

*Nextcord

naive briar
#

!d discord.Interaction.edit_original_response

unkempt canyonBOT
#

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

Edits the original interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.
naive briar
#

It's just a fork that's not any different than discord.py

white citrus
#

See

slate swan
#

i dont think nextcord uses response

#

they still use message

white citrus
#

!d nextcord.Interaction.edit_original_message

unkempt canyonBOT
#

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

Edits the original interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.InteractionMessage.edit "nextcord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.
white citrus
#

So where do i have to use it?

slate swan
#

?

white citrus
#

Instead of self._help_command.response.edit(view=self)?

slate swan
#

i suggest you not just copy and paste code. the code you shown literally has

await interaction.edit_original_message(embed=embed)

in it so if you wrote you would know how to edit a message. Take the time to actually learn it, it can be fun

white citrus
#

Only self

slate swan
vale wing
unkempt canyonBOT
#

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

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

โ€ข status

โ€ข activity

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

!d discord.Member.activities then this

unkempt canyonBOT
#

The activities that the user is currently doing.

Note

Due to a Discord API limitation, a userโ€™s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.

slate swan
#

ohhh

#

wait before, after is like a member attribute?

spice jewel
#

hey everyone,
I just need some help with a feature im unsure of

vale wing
#

Sure

#

Members intent on?

spice jewel
#
@spooky.command()
async def remove(ctx, member: discord.Member):
    guild = spooky.get_guild(1066633798046986300)
    role1 = guild.get_role(1066646265737248908) 
    role2 = guild.get_role(1066646277397434419)
    await ctx.send("What is the reason for removing?")
    response = await spooky.wait_for_message('message')
    if response.content  == 'none' and ctx.author == response.author:
        await ctx.send("no reason selected")
        await member.remove_roles(role )
        await member.edit(nick=None)
        dynamic_timestamp = discord.utils.format_dt(datetime.now(), style="R")
        remove=discord.Embed(
            title="โ €โ € User Removed โœฆ", 
            description=f"{member.mention} has been removed", 
            color=discord.Color(0xac0101)
            )
        remove.set_thumbnail(url=member.avatar)
        remove.add_field(
            name="Removed by:",
            value=f"{ctx.author.mention}"
        )
        remove.add_field(
            name="Date removed:",
            value=dynamic_timestamp,
            inline=True
   
        await ctx.send(embed=remove)
    else:
      (literally same thing happens)
      await ctx.send(embed=remove)```
#

I'm trying to make a feature which can remove roles from users, I'm trying to make the bot ask the person using the cmd a question (what is the reason for removing?) the bot should then store that as a variable (response) so it can be used in the embed later. Instead of recognising the users response and proceeding by sending the embed, the bot does nothing

vale wing
#

Your issue is you need to use check

spice jewel
vale wing
#
msg = await bot.wait_for("message", check=lambda x: x == ctx.author)
slate swan
#

How do I only get the customactivity name

#

rather than the entire list

naive briar
#

Get it then

#

That's the captcha or your internet's problem

vale wing
unkempt canyonBOT
#

discord.utils.find(predicate, iterable, /)```
A helper to return the first element found in the sequence that meets the predicate. For example:

```py
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
```  would find the first [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") whose name is โ€˜Mightyโ€™ and return it. If an entry is not found, then `None` is returned.

This is different from [`filter()`](https://docs.python.org/3/library/functions.html#filter "(in Python v3.11)") due to the fact it stops the moment it finds a valid entry.

Changed in version 2.0: Both parameters are now positional-only.

Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.11)")s.
vale wing
#

To be precise py activity = discord.utils.find(lambda x: isinstance(x, discord.CustomActivity), after.activities)

naive briar
#

Who uses forks anymore

#

And for the love of God use f-strings and not +

left dew
#

anyone know why these couldn't be resolved even though they are installed:

naive briar
#

What can't be resolved

#

Be specific

left dew
#

discord.ui, chat_exporter and pytz

naive briar
#

discord.ui is a module fromdiscord.py

#

And datetime already has the same features as pytz

#

And send the error when you're trying to install and an error occurred

left dew
#

there isn't an error, i think its something to do with my interpreter because they worked fine yesterday

naive briar
#

Then I can't tell what's wrong

vale wing
#

Venv issue

unkempt canyonBOT
#
Virtual Environments

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

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

Then, to activate the new virtual environment:

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

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

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

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

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

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
left dew
#

nvm i fixed it. i just fixed my interpreter

slate swan
#

What way could I create a slash command thats prompt only allows a true or false answer?

naive briar
#

Just set bool as type hint