#discord-bots

1 messages · Page 209 of 1

echo wasp
#

ok

slate swan
#

Side note: best off not naming a Member object "user", a member is not the same as a user

echo wasp
#

I got else

cloud dawn
potent spear
# echo wasp I got else

alr, then you know what's wrong, right? your if statement is not True, most likely the
if payload.emoji.name == ":Giveaways:"

slate swan
#

what about try except will that work?

potent spear
potent spear
#

(above the if statement ofc 🧠 )

cloud dawn
# potent spear It will not
try:# Don't use
    @client.comman# Don't used()# Don't use
    async def check(ctx, user: discord.Member):
        if user.id in requested.find_one():# Don't use
            await ctx.send("User is in the database")# Don't use
        else: # Don't use
            await ctx.send("User is not in the database")# Don't use
except:
    pass
unborn bluff
#

Sending the file alone is ok, but I don't know how to send the image inside the discord.embed, embed.set_image only accepts https, and the attachment url isn't working.

potent spear
slate swan
slate swan
#
try:
    @client.command()
    async def check(ctx, user: discord.Member):
        if user.id in requested.find_one():
            await ctx.send("User is in the database")
        
except:
    async def check(ctx, user: discord.Member):
        await ctx.send("User is not in the database")

???

echo wasp
potent spear
potent spear
slate swan
#

nah it not works

echo wasp
potent spear
unborn bluff
# potent spear show current code again pls
async with self.bot.http_session.get(
    document["sprites"]["front_default"]
) as res:
    sprite = await res.read()
    sprite = Image.open(BytesIO(sprite)).convert("RGBA")
    sprite = sprite.resize((2100, 2100))

    # Paste the sprite onto the background
    x_offset = (bg.width - sprite.width) // 2
    y_offset = (bg.height - sprite.height) // 2
    bg.paste(sprite, (x_offset, y_offset), mask=sprite.split()[3])

    result_buffer = BytesIO()
    bg.save(result_buffer, format="JPEG")
    result_buffer.seek(0)

file = discord.File(
    result_buffer, filename=f"a_wild_{document['name']}_appeared!.jpeg"
)
embed = discord.Embed(
    title=f"A wild {document['name']} has appeared!", color=0x05E1E1
)
embed.set_image(url=f"attachment://{file.filename}")
await ctx.send(embed=embed, file=file)

c':

slate swan
#

mine didnt worked

potent spear
unborn bluff
unborn bluff
potent spear
#

look closely

cloud dawn
unkempt canyonBOT
#

discord.ext.commands.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.

A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
unborn bluff
potent spear
#

you just need to pass your file object

languid siren
#

discord py is soooooo weird

#

can someone help me make a bot that simply says hi when I type hi??? WHy is it so hard?

potent spear
#

good code examples are key for beginners

cloud dawn
#

@slate swan Look above for some examples. ```py
@Cog.listener('on_command_error')
async def err_handler(self, ctx: Context, error: Any) -> None:
# if command has local error handler, return
if hasattr(ctx.command, 'on_error'):
return

    # Get original error instead of a global Invoke error
    error = getattr(error, 'original', error)

    # Standard debug to log to catch unknown errors
    logger.debug(type(error))

    if isinstance(error, CommandNotFound):
        logger.debug(f"{ctx.author} this command does not exist")
    elif isinstance(error, HTTPException):
        error.text = error.text.replace("\n", " ")
        logger.warn(f"HTTPException: {error.text}")
    elif isinstance(error, NotFound):
        error.text = error.text.replace("\n", " ")
        logger.warn(f"NotFound: {error.text}")
    elif isinstance(error, CheckFailure):
        logger.debug(f"Check failed for {ctx.author} most likely has no permission to execute this")
    else:
        logger.error(error)
languid siren
#

i have found 0 code examples that work

potent spear
cloud dawn
#

GIT CLONE

#

Petition for everyone to work with docker so I don't have to set anything up.

languid siren
#

is there any good discord py tutorial?

potent spear
#

the docs

languid siren
#

lol

potent spear
#

don't use YT

languid siren
#

Il try

cloud dawn
#

What are you trying to do? @languid siren

echo wasp
#

how do i define a global value?

#

i tried using reaction_roles = someid

#

and it says that is not defined

cloud dawn
#

Uhhh

#

How are you using it? I don't really want to recommend using global since there are way better methods.

echo wasp
#

if not more

languid siren
thin raft
#

send code

#

probably just use self @cloud dawn

cloud dawn
#

😔

thin raft
potent spear
languid siren
#

thanks a lot. I will check it all out.

potent spear
#

yeah, having basic python knowledge is key here

languid siren
#

async/await seems cool xD

potent spear
#

it is

cloud dawn
echo wasp
#

reaction_roles == someid

cloud dawn
#

But from where?

potent spear
#

a list can't be equal to a single value...

cloud dawn
echo wasp
#

i was thinking it worked liked this

potent spear
cloud dawn
#

I still don't know how or where reaction_roles is created and compared to an id.

echo wasp
#

i want reaction_roles to have the id value

cloud dawn
#

Yeah okay but in what context do you want reaction_roles?

magic granite
#

How bad is the idea of enabling all intents for a bot? And why?

cloud dawn
potent spear
magic granite
#

Might as well enable all on development and restrict down based on final feature list

cloud dawn
#

You'd be surprised how much a bot can do without any intents.

potent spear
echo wasp
languid siren
#

documentation is really helpful indeed. Im so hyped nwo

cloud dawn
potent spear
#

on github are examples too which aren't documented on the website

echo wasp
#

self.reaction_roles?

cloud dawn
#

🎊 Anotherone converted to the ways of the docs.

cloud dawn
potent spear
#

mhm, then your reaction_roles will be an attribute of your cog class

#

=> you'll be able to access that attribute in different commands / events in the same cog

magic granite
#

Considering the intensive moderation plugin I'm adding....yea, I'm gonna need them

cloud dawn
magic granite
#

Safeguards against deletes and backlogging message on-demand I guess ¯_(ツ)_/¯

#

I'm not using Carl/Dyno/what-have-you for a reason

#

Mainly, I hate their dreadful UI/UX

unborn bluff
# potent spear look closely

Can't get it to work, it still sends the image outside the discord.embed. I guess I'll just save it on disk :'(

potent spear
magic granite
#

More like I wrote too much PCRE regex and I can't get rid of my lookarounds

unborn bluff
# slate swan show code
async with self.bot.http_session.get(
    document["sprites"]["front_default"]
) as res:
    sprite = await res.read()
    sprite = Image.open(BytesIO(sprite)).convert("RGBA")
    sprite = sprite.resize((2100, 2100))

    # Paste the sprite onto the background
    x_offset = (bg.width - sprite.width) // 2
    y_offset = (bg.height - sprite.height) // 2
    bg.paste(sprite, (x_offset, y_offset), mask=sprite.split()[3])

    result_buffer = BytesIO()
    bg.save(result_buffer, format="JPEG")
    result_buffer.seek(0)

file = discord.File(
    result_buffer, filename=f"a_wild_{document['name']}_appeared!.jpeg"
)
embed = discord.Embed(
    title=f"A wild {document['name']} has appeared!", color=0x05E1E1
)
# embed.set_image(url=f"attachment://{file.filename}")
await ctx.send(embed=embed, file=file)

Found this question but it haven't been answered yet :') https://stackoverflow.com/questions/74164047/send-a-pillow-image-in-a-discords-embed

rancid tulip
#

To make sure the image is added to the embed before the message is sent, you can try creating the discord.Embed object first, setting the image URL to None, and then adding the image as a file attachment to the message using the add_field() method. Here's an example: ```embed = discord.Embed(
title=f"A wild {document['name']} has appeared!",
color=0x05E1E1
)
embed.set_image(url=None)
file = discord.File(result_buffer, filename=f"a_wild_{document['name']}_appeared!.jpeg")
embed.set_footer(text=f"Image credit: {image_credit}")
await ctx.send(
embed=embed.add_field(
name="Image",
value=f"Here's a picture of {document['name']}!",
inline=False
).set_image(url=f"attachment://{file.filename}"),
file=file
)


I hope this helps! Let me know if you have any further questions.
slate swan
#

and yeah the method works for sure

shrewd apex
slate swan
#

i just came online wait

river plank
#

how do i fix the "ServerSelectionTimeoutError" in pymongo ?

shrewd apex
#

also ur internet has proper ssl certification and stuff

river plank
#

uh

#

im using it thru replit

#

like mongodb atlas

warm summit
#

Umm hey suppose i want to install discord.py on host server what should I write in requirements.txt
Just discord.py or...

river plank
echo wasp
#

how do i remove a reaction from a different message?

honest shoal
unkempt canyonBOT
#

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

Remove a reaction by the member from the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").

If the reaction is not your own (i.e. `member` parameter is not you) then [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") is needed.

The `member` 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: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
echo wasp
honest shoal
unborn bluff
#

I changed the filename and it worked... The problem was the "!" in the filename... ,_,

#

tysm ,_,

echo wasp
honest shoal
unkempt canyonBOT
#
Nope.

No documentation found for the requested symbol.

honest shoal
#

!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 "discord.Message") from the destination.
echo wasp
#

like that?

honest shoal
honest shoal
echo wasp
honest shoal
#

oh

#

then just disable the permission from discord to add reactions instead of making a long mess

echo wasp
#

and i will but just in case someone with admin perms adds one

honest shoal
#

ok

honest shoal
echo wasp
#

of the channel

honest shoal
#

because that's how it works

echo wasp
slate swan
#

!d discord.ext.commands.Bot.get_channel Use this to return a channel/thread by ID

unkempt canyonBOT
echo wasp
#

so how do i format this with fetch message?

honest shoal
#

if you get the channel inside a variable called x, then it will be:

message = await x.fetch_message(id)```
#

id being the message id

echo wasp
#

ok thanks

thin raft
#

Can you detect when a member gets timeouted?

#

member_update mb

slate swan
#

!d discord.on_member_update

unkempt canyonBOT
#

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

This is called when one or more of the following things change...
slate swan
#

You can compare the timeout of before and after

thin raft
#

idk why I didn't check the docs before asking mb

thin raft
slate swan
slate swan
#

how would you copy permissions_for a channel to a new temp channel? like each possible role that has access to that channel carries over to the temp channel?

lost cliff
lost cliff
queen wren
#

!d discord.TextChannel.clone

unkempt canyonBOT
#

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

Clones this channel. This creates a channel with the same properties as this channel.

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

New in version 1.1.
queen wren
#

This also works with discord.VoiceChannel, discord.StageChannel, etc.

slate swan
queen wren
#

Yes.

#

But it's the easiest way ig.

vale wing
#

!d discord.TextChannel.edit

unkempt canyonBOT
#

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

Edits the channel.

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

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

Changed in version 1.4: The `type` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead...
vale wing
#

The solution with mininum API calls would be just to create a new channel with parsing overwrites from the base instead of cloning it

sick birch
lost cliff
fair shuttle
#

im sorry if thats stupid lol im learning buttons but i dont understand this error

sick birch
#

discord.ui.View

#

!d discord.Intents

unkempt canyonBOT
#

class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.

Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").

New in version 1.5.
sick birch
#
intents = discord.Intents.default()
intents.message_content = True # required for prefix commands

client = discord.Client(intents=intents)
# OR
bot = commands.Bot(..., intents=intents)
fair shuttle
#

i was also thinking do i really need to add that for the roles buttons work?

sick birch
fair shuttle
#

oh alr

slate swan
#

Are you coding on android

fair shuttle
calm sapphire
#

idek

dense jackal
#

Hi! When a user types in the bot’s dm, this text appear. From there, they can choose if they want to create a ticket or cancel the interaction. Although, we found a glitch that if you send 2 messages, the text will sent twice and then, you will be able to create 2 tickets at once. Can someone help me to code so that the embed stops resending everytime they type in? My script is: https://paste.pythondiscord.com/yidukekala

fair shuttle
#

did i do anything wrong?

smoky sinew
#

you cannot call your view and your command the same thing

#

name it RolesView or something like that

silver quest
#

please @silver quest me otherwise i wont see

regal cove
#

is it possible to use server specific emojis in buttons and selections?

calm sapphire
#

guys

#

is it possible to make a lyric song bot where u search a lyric

calm sapphire
#

???

dense jackal
#

Hi! When a user types in the bot’s dm, this text appear. From there, they can choose if they want to create a ticket or cancel the interaction. Although, we found a glitch that if you send 2 messages, the text will sent twice and then, you will be able to create 2 tickets at once. Can someone help me to code so that the embed stops resending everytime they type in? My script is: https://paste.pythondiscord.com/yidukekala

turbid canopy
fair shuttle
#

any1 can help w that i have the button appear but it says the interaction has failed

smoky sinew
#

@silver quest

smoky sinew
#

so swap those two around

fair shuttle
#

ty:)

blazing flint
#

how would I include a variable in a .path

woeful magnet
#

Hello What do I have to do to user async in thread

graceful ermine
#

Hey, I need help

Ignoring exception in view <Regenerate timeout=180.0 children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Regenerate' emoji=None row=None>:
Traceback (most recent call last):
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\ui\view.py", line 370, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\berka\Desktop\Eagle Bird GPT\main.py", line 181, in regenerate
    await self.update_image(interaction)
  File "C:\Users\berka\Desktop\Eagle Bird GPT\main.py", line 177, in update_image
    await msg.edit(content="Content generated", file=nextcord.File(image, "generatedImage.png"), view=self)
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\interactions.py", line 1180, in edit
    message = await self._state._interaction.edit_original_message)

#

code:

class Regenerate(nextcord.ui.View):
    def __init__(self, prompt):
        super().__init__()
        self.prompt = prompt

    async def update_image(self, interaction: nextcord.Interaction):
        await interaction.response.defer()
        
        ETA = int(time.time() + 60)

        try:
            msg = await interaction.edit_original_message(content=f"This could take some time, go take a rest and let me do my thing!!! ETA: <t:{ETA}:R>")
        except nextcord.NotFound:
            # Interaction has expired or webhook has been deleted, create a new interaction object
            interaction = await self.bot.fetch_interaction(interaction.id, interaction.token)
            msg = await interaction.edit_original_message(content=f"This could take some time, go take a rest and let me do my thing!!! ETA: <t:{ETA}:R>")
            
        async with aiohttp.request("POST", "https://backend.craiyon.com/generate", json={"prompt": self.prompt}) as resp:
            r = await resp.json()
            images = r['images']
            image = BytesIO(base64.decodebytes(images[0].encode("utf-8")))
            await msg.edit(content="Content generated", file=nextcord.File(image, "generatedImage.png"), view=self)

    @nextcord.ui.button(label="Regenerate", style=nextcord.ButtonStyle.success)
    async def regenerate(self, button: nextcord.ui.button, interaction: nextcord.Interaction):
        await self.update_image(interaction)
#
 
@bot.slash_command(name="describe", description="describe something and I will turn it into a picture!")
async def describe(interaction: nextcord.Interaction, prompt: str):
    view = Regenerate(prompt)
    ETA = int(time.time() + 60)
    msg = await interaction.response.send_message(f"This could take some time, go take a rest and let me do my thing!!! ETA: <t:{ETA}:R>")

    async with aiohttp.request("POST", "https://backend.craiyon.com/generate", json={"prompt": prompt}) as resp:
        r = await resp.json()
        images = r['images']
        image = BytesIO(base64.decodebytes(images[0].encode("utf-8")))
        await msg.edit(content="Content generated", file=nextcord.File(image, "generatedImage.png"), view=view)```
#

Everytime I press the button the regenerate a new image it keeps on doing that!

smoky sinew
#

it's cut off right before the actual error appears

graceful ermine
#

that's what it gave me

smoky sinew
#

check again

graceful ermine
#

Okay!

#

@smoky sinew

#
Ignoring exception in on_connect
Traceback (most recent call last):
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\client.py", line 490, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\client.py", line 2459, in on_connect
    await self.sync_application_commands(
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\client.py", line 2273, in sync_application_commands
    await self._connection.sync_application_commands(
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\state.py", line 807, in sync_application_commands
    await self.register_new_application_commands(data=data, guild_id=guild_id)
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\state.py", line 1014, in register_new_application_commands
    await self.register_application_command(app_cmd, guild_id)
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\state.py", line 1049, in register_application_command
    raise e
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\state.py", line 1045, in register_application_command
    raw_response = await self.http.upsert_global_command(self.application_id, payload)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^```
#
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\http.py", line 400, in request
    raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In name: Command name is invalid
Eagle Bird GPT (Dev)#2353 is now online!
Ignoring exception in view <Regenerate timeout=180.0 children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Regenerate' emoji=None row=None>:
Traceback (most recent call last):
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\ui\view.py", line 370, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\berka\Desktop\Eagle Bird GPT\main.py", line 181, in regenerate
    await self.update_image(interaction)
  File "C:\Users\berka\Desktop\Eagle Bird GPT\main.py", line 177, in update_image
    await msg.edit(content="Content generated", file=nextcord.File(image, "generatedImage.png"), view=self)
  File "C:\Users\berka\AppData\Local\Programs\Python\Python311\Lib\site-packages\nextcord\interactions.py", line 1180, in edit
    message = await self._state._interaction.edit_original_message(
                    ^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'ConnectionState' object has no attribute '_interaction'```
smoky sinew
#

interesting

graceful ermine
#

How could we fix this?

smoky sinew
#

i'm not sure i will look into it

dense jackal
#

My bot is running just once and I only have one python open

graceful ermine
#

@dense jackal send your code

#

I can't see it

dense jackal
#

Oh wtf

smoky sinew
#

oh nvm that's a different screenshot

#

why are you back to the other code btw

dense jackal
#

Idk

smoky sinew
#

why so

dense jackal
#

Idk ask @hushed galleon

hushed galleon
dense jackal
hushed galleon
dense jackal
#

how do I even see if my bot is running twice?

hushed galleon
#

that can get tough since it could be hosted in the background on your computer or on another computer entirely

hushed galleon
#

that might work

#

your code doesnt look like it should be replying to you twice

smoky sinew
hushed galleon
#

might want to discuss in #databases instead but the point of SQLite waiting is to maintain ACID, and with a single connection you'll immediately violate those invariants unless you put your own lock on it, plus i described the write-ahead log where readers don't need to wait (while having an isolated transaction)
(and with short-lived connections the pause will only be momentary)

(discussing here
#databases message)

smoky sinew
dense jackal
#

Hi! When a user types in the bot’s dm, this text appear. From there, they can choose if they want to create a ticket or cancel the interaction. Although, we found a glitch that if you send 2 messages, the text will sent twice and then, you will be able to create 2 tickets at once. Can someone help me to code so that the embed stops resending everytime they type in? My script is: https://paste.pythondiscord.com/yidukekala

hushed galleon
#

^ previously suggested solution

rare echo
hushed galleon
#

if you're struggling to implement it, perhaps your friend could help out?

dense jackal
#

Hes not available for the next weeks

#

And hes not really experienced with discord py

#

He did his best but

rare echo
#

when you send the message you can append it to a dictionary with perhaps the userid and either a toggle, or the message id, and when its done remove it from the dict

dense jackal
#

Should I go check on youtube how to do that?

rare echo
#

or you might be able to get away with a list of the user id

#

if you dont know about dictionaries im sure theres resources, idk any off the top of my head

dense jackal
#

I see

#

Im new to that python stuff 😅

#

Im trying to create a bot for my community

rare echo
#

you might be able to get away with just appending a list


buffer = []
buffer.append(ctx.user.id) # stopping them from making another
do the stuff
buffer.remove(ctx.user.id) # Allowing them to request another

youd just have to run checks on what you need to do

#

!resources

unkempt canyonBOT
#
Resources

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

rare echo
#

ima have a look

dense jackal
dense jackal
rare echo
#

this gives a quick rundown, just imagine using the userid

youll essentially check if the userid is in the list, if it is, a simple "you already have one"
if its not youll be adding them to the list and opening a message/ticket

blazing flint
#

help making a mute command?

woeful magnet
#

can anybody tell me how to make giveaway bot?

vale wing
#

Better invite one, why reinvent the wheel

vale wing
# woeful magnet can anybody tell me how to make giveaway bot?

Making a giveaway bot is not a simple task, but here are general steps you need to follow in order to create a giveaway bot:

  1. Create development basic tools, including bot subclass, database methods and other required things (if you are disnake user you can use my template https://github.com/Exenifix/disnake-bot-template-postgres)
  2. Add tables into database that will store users who participated in a giveaway and additional data
  3. Create giveaway system - how users would enter giveaway and how bot would give reward to them
woeful magnet
vale wing
#

There's none I hate them

#

Repo is a template for speeding up development, empty bot so basically

woeful magnet
#

oops

woeful magnet
#

If I hire bot dev to make it , then how much do I pay for that?

fair shuttle
#

quick question tho cuz i cant find anything about that lol for reaction roles i want to make some with select menu is that the same thing of the button so i can js replace that by the good thing or its a whole diff thing?( also if you have the doc would b cool cuz i cant find it

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.

vale wing
#

The point of programming is not to find a solution but think of one

#

Finding applies too but to subtasks

vale wing
#

!rule paid

unkempt canyonBOT
#

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

vale wing
shrewd fjord
#

!paid

shrewd apex
woeful magnet
shrewd apex
#

asyncio and apis u would have to google it up

river plank
#

heyy

#

ok so the database works in the morning/afternoon

#

then i get the server timeout error

vale wing
#

And how do you connect to it

shrewd apex
#

it goes rouge in the night werewolf

vale wing
#

When the database is sus

vale wing
river plank
vale wing
#

Dunno about that much but will try to figure out if nobody else can help

shrewd apex
#

mongodb don't do that amongusred

vale wing
#

How do you connect to it

river plank
#

well

#

mongoclient

vale wing
#

I mean in code

shrewd apex
#

one reason could be ur ip changed and in network acess u are limited

river plank
#

well

vale wing
#

Is it on localhost or remote

river plank
#

im using replit, with mongodb atlas

vale wing
#

Oh heck

#

Just don't use replit, easy solution

river plank
#

welp

#

uh hm

shrewd apex
#

^^

quick gust
#

though iirc you'll need a card

river plank
#

oh right

#

thanks

vocal snow
#

because response isn't the json data

#

it's a Response object

#

you can use it's .json() method

#

although for a discord bot you should be using an async http client like aiohttp instead of requests

shrewd apex
#

zeffo expert in this field pikachu_sip

river plank
#

shi

#

alr alr

slate swan
#

?

#

so i did a role slash command that takes the role id and gets it into an embed -

    @nextcord.slash_command(name="helpme-role", description="Set the helpme role")
    async def helpmerole(self,interaction:nextcord.Interaction,
    role_: nextcord.Role = nextcord.SlashOption(name='role', description='Please select a role', required=True)):
        if interaction.user.guild_permissions.administrator:
            async with aiosqlite.connect("main.db") as db:
                async with db.cursor() as cursor:   
                    await cursor.execute('SELECT role_id FROM role WHERE guild = ?', (interaction.guild.id,))
                    role = await cursor.fetchone()
                    if role:
                        await cursor.execute('UPDATE role SET role_id = ? WHERE guild = ?', (role_.id, interaction.guild.id,))
                    else:
                        await cursor.execute('INSERT INTO role (role_id, guild) VALUES (?, ?)', (role_.id, interaction.guild.id,))
                await interaction.response.send_message(f"Successfuly set the helpme staff role to - {role_.mention}")
            await self.bot.db.commit()
        else:
            await interaction.response.send_message("You need the `administrator` permission to use this slash command!")

when im changing the role it keeps the same role'

slate swan
#

updating it

#

do i need to remove or to update it is enough

thin raft
#

send screenshot of SELECT * FROM role;

slate swan
#

did that

thin raft
#

and send code as text not screenshot

slate swan
#

i dont have the SELECT * FROM role

thin raft
#

execute SELECT * FROM role; and send the output it sends

#

do you know SQL?

slate swan
#

okay

#

yes

slate swan
#

in the command that takes the role or the command that tags it

thin raft
#

how do you check the contents of a table?

slate swan
#

wdym

#

how do i check the coloumns?

thin raft
#

the content of the table

#

how do you check it?

slate swan
bold python
#

anyone can maybe help me with my discord bot`? hes supposed to play Music. But he just enters and doesnt play music. In the Terminal i get a message saying " ERROR: '!play' is not a valid URL. Set --default-search "ytsearch" (or run youtube-dl "ytsearch:!play" ) to search YouTube "

#

I cannot find any help on google so maybe here

unkempt canyonBOT
#

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

bold python
#

ah isee

#

so music bto is breaking law

vale wing
#

Yes that's why the feature was disabled on mee6 and several music bots were shut down

rare echo
#

i mean only law realistically when money is involved, but it breaks their tos

vale wing
#

Money is involved cause playing music from youtube does that without ads

frosty parrot
#
    def __init__(self):
        options = [
            discord.SelectOption(label="Red", description="Red is a colour", emoji=":clashgoblin35:", value="red"),
            discord.SelectOption(label="Blue", description="Blue is a colour", emoji=":clashduh:", value="blue"),
            discord.SelectOption(label="Green", description="Green is a colour", emoji=":clashhuh5:", value="green"),
            discord.SelectOption(label="Yellow", description="Yellow is a colour", emoji=":clashkiss45:", value="yellow"),
            discord.SelectOption(label="Purple", description="Purple is a colour", emoji=":clashhappy:", value="purple"),
        ]

        super().__init__(placeholder="Select an option", options=options)

    async def callback(self, interaction: discord.Interaction):
        await interaction.response.send_message(f"You selected {self.values[0]}")

    @discord.ui.button(label="Close", style=discord.ButtonStyle.red, row=1)
    async def close(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message("closed the dropdown", ephemeral=True)
        self.stop()

if __name__=="__main__":
    bot = MyBot(command_prefix="-", intents=discord.Intents.all())
    
    
    #  MESSAGE COMMANDS

    @bot.command()
    async def dropdown(ctx):
        view = discord.ui.view(timeout=60)
        view.add_item(Dropdown())

        await ctx.send("Select a colour", view=view)```
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'module' object is not callable

vale wing
#

But um actually we don't have youtube ads in Russia 🤓👍

naive briar
#

Do you still have YouTube at this point

vale wing
#

Yes

unkempt canyonBOT
#
Traceback

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

A full traceback could look like:

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

If the traceback is long, use our pastebin.

vale wing
bold python
vale wing
#

But videos are okay and there are no ads

naive briar
vale wing
#

Legal way to avoid ads in youtube is get a russian vpn

shrewd fjord
#

Or just live in russia

bold python
#

But maybe yall can help me with this. It says ERROR "!play" is not a valid URL. SO the Bot joins. but thats about it.

#

its got nothin to do with yt

naive briar
#

It's clearly an error from ytdl

vale wing
#

Nope sorry, it is still a project that violates ToS

naive briar
#

From your previous message

vale wing
#

Once we know we know

bold python
#

Shhh its nothin about yt :l

#

well ok anyways thx

vale wing
#

tos-and-pp is a very good repository

frosty parrot
#

par error isme ayahai wo pata hai

slate swan
#

English….

frosty parrot
slate swan
frosty parrot
#

wait

#
  File "C:\Users\BADAL NAG\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\BADAL NAG\Desktop\discord\discrdbot\cogs\error.py", line 38, in on_command_error
    raise error
  File "C:\Users\BADAL NAG\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1349, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\BADAL NAG\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\BADAL NAG\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'module' object is not callable←[0m```
warm summit
#

How can I add emoji buttons to embed

slate swan
#

!d discord.ui.Button

unkempt canyonBOT
#

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

New in version 2.0.
slate swan
#

You can add emoji attribute

warm summit
#

Ohh ok

bold python
#

is it possible that YT dl is out of service ?

#

i foudnthe error in my code and then it told me that i needed tthe newest verion, So i upgraded it. it still doesnt work. Im not askin for advice about my discord bot im asking if its possible that youtube.dl no longer works?

slate swan
#

why do i get error with this code? @bot.command() async def commands(message): if message.content.startswith('!commands'): embed = discord.Embed(colour=0x9B59B6, title="List of Commands", type='rich', url=None, description="Hello", timestamp=None) await message.channel.send(embed=embed)

thin raft
unkempt canyonBOT
#

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

slate swan
#

wait nevermind

slate swan
#

i think i figured it out wait

thin raft
#

you are mixing two concepts

slate swan
#

Yeah i figured it out now

bold python
#

waht was it

warm summit
naive briar
#

Yes? And why don't just test it

warm summit
naive briar
#

Send the code

terse stream
#

can this make me join different servers my its self?

naive briar
#

What

shrewd fjord
#

This application let you join other server without you even knowing

terse stream
naive briar
#

Oauth2

warm summit
terse stream
naive briar
terse stream
naive briar
#

What

warm summit
terse stream
fair shuttle
naive briar
naive briar
naive briar
#

Just ask here

terse stream
#

nvm

fair shuttle
#

oh yeah i didnt see dat was cstom

warm summit
naive briar
#

Do you know custom emoji formats

warm summit
#

I did with I'd too

naive briar
#

Then what happened

warm summit
#

Same

naive briar
#

It has be to exactly

<:emoji_name:id>
#

Change it back and see what happens

warm summit
fair shuttle
#

it suppose to work if you did that tho

warm summit
#

In " " right?

terse stream
#

whats this suppose to dO?

naive briar
#

Yes?

terse stream
#

redirect url

warm summit
#

Still not working

naive briar
#

Send the code and the error

warm summit
fair shuttle
#

you could do windows shift S for screenshot lol

warm summit
naive briar
warm summit
naive briar
#

And why is self not the first argument of that method

warm summit
#

📩

naive briar
#

How did you get its ID then

#

It has no ID

#

And the

<:emoji_name:id>

is only for custom emojis

warm summit
#

Ohh I think I pasted message id

fair shuttle
#

like that

#

if you have custom emoji

warm summit
naive briar
#

And?

#

I don't have any code or error to tell what's wrong

#

And just put the emoji in if it's a default one

terse stream
#

what should i do about this?

fair shuttle
fair shuttle
#

great

terse stream
#

😑

#

anyone?

fair shuttle
#

yea?

#

whats going on

slate swan
#

question about views and buttons.
if i want async def on_button_click:to take the label of the button, change a channel id's channel name, how would that work? i'm like trying to understand discord.ui.buttons and views, but i don't get how they work still x.x

naive briar
#

What library is this

slate swan
#

discord.ui? Button, View?

naive briar
#

That doesn't answer the question

#

What library is it from? Like discord.py, disnake, ...

slate swan
naive briar
#

There's no such events as on_button_click

slate swan
#

so instead of making a function, i should use discord.Interaction?

naive briar
#

I don't know what that means

slate swan
#

ok. i'll just explain. so i made an embed generator for 10 names at a time. the 10 names will generate into buttons, i'm trying to convert this to update the name of two channels using dictionary comprehension.
https://paste.pythondiscord.com/cokagiqago

i just don't know where i'm going wrong with the discord.Interaction

naive briar
#

You did not give the buttons their callbacks

#

!d discord.ui.Button.callback

unkempt canyonBOT
#

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

The callback associated with this UI item.

This can be overridden by subclasses.
slate swan
#

FacePlam
thank you.

unkempt mauve
slate swan
#

you'd define the timeout in the init/ super init then when you call the view, timeout = None

class ChannelNameView(View):
    def __init__(self, channel_data_dict, channel_id, names, best_name, timeout=180.0):
        super().__init__(timeout=timeout)

view = ChannelNameView(channel_data_dict, channel_id, names, best_name, timeout=None)

atleast.. that's how i did it.

slate swan
warm summit
#

How can I fetch the channels in a guild

slate swan
slate swan
unkempt canyonBOT
thin raft
#

!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 "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 "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 "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "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.
thin raft
#

@green pivot

warm summit
thin raft
unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

thin raft
#

!traceback

unkempt canyonBOT
#
Traceback

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

A full traceback could look like:

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

If the traceback is long, use our pastebin.

thin raft
#

!d discord.Guild.channels

unkempt canyonBOT
thin raft
#

it doesn't have any property named name

karmic nimbus
#
from discord_ui import Components, Button, SelectOption, SelectMenu

why this always errors? module 'discord' has no attribute 'StoreChannel'

slate swan
#

dont use third party libraries

karmic nimbus
thin raft
#

remove discord-ui

#

and use discord.ui

queen wren
warm summit
#

How to get list of channels of guild in which interaction was performed

quaint scaffold
#

!d discord.Guild.channels

unkempt canyonBOT
quaint scaffold
#

Being able to understand the docs is a very valuable skill

river plank
#

how do i get the name of both attacks?

vocal snow
#

as what datatype

slate swan
unkempt mauve
#

quick question, does restarting your bot resets command cooldown of slash commands (app_commands)?

warm summit
#
  async def hi(self, interaction: discord.Interaction, button: discord.Button):
    c = []
    for channel in interaction.guild.text_channels:
      c.append(channel.name)
    print(c)
    if f"{interaction.user}" in c:
      await interaction.response.send_message(content = "channel exist", ephemeral = True)
    else:  
      await interaction.guild.create_text_channel(f'{interaction.user}')
      await interaction.response.send_message(content = "channel dosnt exist", ephemeral = True)```
unkempt mauve
warm summit
vale wing
#

Write the data on disk

unkempt mauve
vale wing
#

Mm you will need custom cooldown first of all most likely

unkempt mauve
#

i will use db then

vale wing
#

Idk what's it named

#

I will search for that rq

#

!d discord.app_commands.checks.dynamic_cooldown

unkempt canyonBOT
#

@discord.app_commands.checks.dynamic_cooldown(factory, *, key=...)```
A decorator that adds a dynamic cooldown to a command.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and return a value that is used as a key to the internal cooldown mapping.

If a `factory` function is given, it must be a function that accepts a single parameter of type [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown "discord.app_commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.

Both `key` and `factory` can optionally be coroutines.
slate swan
#

I think its discordapp commands but not sure

#

oh it is

#

pip install -U discord-py-slash-command

#

u did that?

sick birch
#

I thought discord_slash was deprecated

#

Why do you need ctx

#

Interaction gives all of it for you

#

Interaction is the same thing

#

Pretty much

river plank
vocal snow
#

what datatype do you want the names as i mean

river plank
#

oh

vocal snow
#

do you want them in a list?

river plank
#

sorry

#

yea sure

vocal snow
river plank
vocal snow
#
for attack in attacks:
    name = attack["name"]
river plank
#

oh

#

right

vocal snow
#

you could also use a list comprehension; ```py
[atk["name"] for atk in attacks]

lyric crystal
#

Quick question:
Do I need PyCharm to program Discord Bot? Or is Visual Studio Code okay?

vocal snow
sick birch
#

Whichever you're more comfortable with

scarlet aurora
#

can u use ephermal messages in 1.7.3

sick birch
#

Don't believe so

scarlet aurora
#

ok

frosty parrot
#

how can I host my bot free ?

bold python
#

I get this when i try and run my Command but it should be all good. I have everything isntalled and i was just workin on smt else before but now i get this message C:\Users\frede\AppData\Local\Programs\Python\Python311\python.exe: can't open file '

#

any idea as to why

scarlet aurora
#

@sick birch so it's 2.0+ ?

sick birch
#

Yeah

slate swan
#

Only free hosting method is to self-host really.

sick birch
#

Only good free hosting

slate swan
#

Yeah

#

I use Digital Ocean and can recommend them as a good VPS provider

sick birch
#

I'd recommend AWS if you're comfortable with a more complex provider but potentially more services and options

quick gust
sick birch
#

Pretty much negligible

quick gust
#

true

karmic shore
#

Heyy, what does this mean? Does that not exist anymore?

#

Or do I have to get the user object?

slate swan
#

avatar_url got changed to avatar.url at some point I think

karmic shore
#

Ah ok thank you

#

Havent used d.py for a year

#

Yup works, thanks

slate swan
#

Np

warm summit
#

How can I send message in channel created by button interaction within the same function

slate swan
warm summit
unkempt canyonBOT
#

Hey @fair shuttle!

It looks like you tried to attach file type(s) that we do not allow (). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.

Feel free to ask in #community-meta if you think this is a mistake.

fair shuttle
#

oh lol

#

i got this error but i cant find where the ctx is missing lol

slate swan
fair shuttle
#

ohh okok

slate swan
#

Why you are using discord and getting nextcord error

#

Did you import it as discord

fair shuttle
#

yes

#

i did

slate swan
#

Aight then

fair shuttle
#

thats prob a d.py bug

slate swan
#

Do you have d.py installed?

fair shuttle
#

yes i do

slate swan
#

You need to uninstall it

#

You can only have one discord lib installed

stray path
#

Hey what libraries do you guys suggest for creating discord bots? Didn't the main developer of the main library abandon the project or something?

velvet compass
#

They did, but then they started again

#

discord.py, disnake, nextcord are all wrappers for interacting with the discord api

#

Also pycord

stray path
#

Oh alright thanks, which one would you suggest?

velvet compass
#

discord.py seems to be the most used, nextcord and disnake are fine though

stray path
#

Ok, thank you.

fair shuttle
#

any1 know how to fix that in libs? im trying to understand the error

velvet compass
#

Read tracebacks from the bottom up

#

And what is the first part of the traceback

fair shuttle
velvet compass
#

Hmmm. And what does your code look like?

fair shuttle
#

like this

#

i wanted to create reaction roles w select menu

velvet compass
#

Somewhere you are missing ctx

#

Or it is not being passed correctly

sick birch
fair shuttle
#

nope

sick birch
#

Why is it in a class?

fair shuttle
#

sm1 told me it was suppose to be in a class lol

sick birch
#

If it's not supposed to be part of a cog then it isn't supposed to be in a class

fair shuttle
#

so i need to remove the class?

sick birch
#

Yes, and the initializer

fair shuttle
#

? or i need to add something else?

gusty flax
fair shuttle
#

yeah

gusty flax
#

Cause idk what’s happening there

fair shuttle
#

and this is the whole error

gusty flax
#

Can u send a pastebin

unkempt canyonBOT
fair shuttle
glad cradle
fair shuttle
gusty flax
#

What the @fair shuttle

#

What’s going on in ur select view

fair shuttle
#

idk lmao the dude typed all that 💀

#

i tought he was helping me

#

but ig no😂

gusty flax
fair shuttle
#

oh

gusty flax
#

Get rid of that

#

And

#

Do commands.command

fair shuttle
gusty flax
#

For ur command decorator

fair shuttle
#

this one?

gusty flax
#

No. The role stuff

fair shuttle
#

oh larr

#

alrr

#

i have to get rid of that too?

gusty flax
fair shuttle
#

it was the selectView part

#

cuz it was basically view = SelectView

gusty flax
#

That’s a whole lot of wrong

river plank
#

How do I loop thru a section of a code ?

gusty flax
#

Tho u can do a task loop if u wanna look smth with discord

river plank
#

Ohhh

#

So just the ordinary while and for loop will do the job ?

slate swan
#

Who is well versed in pythone, please write to me in the bos.

#

need help

smoky sinew
#

you can put any code you want if you're using the tasks extension

slate swan
graceful ermine
#

Hey how would I recode it where after the user pressed an button the code regenerates the same prompt?

code:



@bot.slash_command(name="ask", description="give you a response with the prompt")
async def ask(interaction: nextcord.Interaction, prompt: str):
    await interaction.response.defer()

    view = Regenerate2(prompt)



    openai.api_key = ""
    
    
    
        
    response = openai.Completion.create(
        model="text-davinci-003",
        prompt=prompt,
        temperature=0,
        max_tokens=4000,
        top_p=1,
        frequency_penalty=1,
        presence_penalty=1,
        stop=["Human:", "AI:"]
    )

    AI_Message = response['choices'][0]['text']

    embed = nextcord.Embed(
        title=f"Here is your answer for {prompt}!",
        description=f"{AI_Message}",
        timestamp=datetime.datetime.now(),
        color=nextcord.Color.green()
    )
    embed.set_footer(text=f"By {interaction.user.name}#{interaction.user.discriminator}", icon_url=interaction.user.avatar.url)
    
    await interaction.send(embed=embed, view=view)```
#

class Regenerate2(nextcord.ui.View):
    def __init__(self, prompt):
        super().__init__()

        self.prompt = prompt

    @nextcord.ui.button(label="Regenerate?", style=nextcord.ButtonStyle.success)
    async def Regenerate2(self, button: nextcord.ui.button, interaction: nextcord.Interaction, prompt):
        openai.api_key = ""


        response = openai.Completion.create(
        model="text-davinci-003",
        prompt=prompt,
        temperature=0,
        max_tokens=4000,
        top_p=1,
        frequency_penalty=1,
        presence_penalty=1,
        stop=["Human:", "AI:"]
    )


        AI_Message = response['choices'][0]['text']

        embed = nextcord.Embed(
            title=f"Here is your answer for {prompt}!",
            description=f"{AI_Message}",
            timestamp=datetime.datetime.now(),
            color=nextcord.Color.green()
        )
        embed.set_footer(text=f"By {interaction.user.name}#{interaction.user.discriminator}", icon_url=interaction.user.avatar.url)
        
        await interaction.send(embed=embed)```
slate swan
#

Who is well versed in pythone, please write to me in the bos.
need help

brisk rapids
#

Hey how can I send a custom role in an embed?
Tried this but it just returns none

emoji = str(discord.PartialEmoji(name="128zie", id=1082804342421209171))
#

also tried this

print(client.get_emoji(1082813090929840211))

and this

embed.add_field(name="Interact with buttons to get your roles!", value=f":128zie: - Select your townhall level
slate swan
#

please help me install the pyqiwip2p library correctly. In the bos

#

!pypi pyqiwip2p

unkempt canyonBOT
slate swan
#

just pip install it? and what does this even do

unreal pelican
brisk rapids
#

no I have tried that too and it just sends :128zie:

#

in text form

sick birch
#

You can get that by typing your emoji like usual in Discord, then putting a backslash before it

brisk rapids
#

ok thank you ill try

smoky sinew
brisk rapids
#

is there a way I could do this for a button too?

#

like a discord button?

brisk rapids
#

have a custom emoji in the label of the button

brisk rapids
#

something like this

class StrategistRoleButton(discord.ui.Button):

  def __init__(self):
    super().__init__(style=discord.ButtonStyle.green, label=f"Strategist :128zie:")

  async def callback(self, interaction: discord.Interaction):
    role = discord.utils.get(interaction.guild.roles, id=strategistRoleId)
    await interaction.user.add_roles(role)
    await interaction.response.send_message(f"You gained the {role.name} role", ephemeral=True)
#

exept this does not work

brisk rapids
#

for some reason it changes the long <:name:id> thing to just the name but you get what i mean

#

let me check

fair shuttle
#

whats wrong?

smoky sinew
#

and Cog is capitalized

gusty flax
#

and why do u have a command inside of your nested class

#

which is inside of a select

frosty parrot
#
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(style=discord.ButtonStyle.red, label="Red")
    async def red_color(self, interaction: discord.Interaction, button:discord.ui.Button):
        red_role = discord.utils.get(interaction.guild.roles, name="Red")

        await interaction.user.add_roles(red_role)

if __name__=="__main__":
    bot = MyBot(command_prefix="-", intents=discord.Intents.all())
    


    @bot.command(name="selfroles")
    async def self_role(ctx):
        await ctx.send("Give your self a role",view = SelfRoles())```
#

command not found

fair shuttle
#

i want to know if its possible to remove a role when we click on it via select menu if any1 has the doc would b apreciate iont find it

bold python
# fair shuttle whats wrong?

import discord
from discord.ext import commands
from discord.ui import Select

class SelectView(discord.ui.View):
def init(self, *, timeout=None):
super().init(timeout=timeout)
self.add_item(Select())

class role(commands.Cog):
def init(self, bot):
self.bot = bot

@commands.command()
async def role(self, ctx):
    await ctx.send("pick a role")
    view = SelectView()
    await ctx.send("View created.")
bold python
# fair shuttle whats wrong?

Regarding the "command 'role' not found" error, it could be because you have not loaded the role cog in your bot. You need to load the cog using bot.add_cog(role(bot)) before running the bot. Don’t know if your problem already solved. If not then try this maybe

unkempt canyonBOT
#

class discord.ui.RoleSelect(*, custom_id=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None)```
Represents a UI select menu with a list of predefined options with the current roles of the guild.

Please note that if you use this in a private message with a user, no roles will be displayed to the user.

New in version 2.1.
naive briar
#

And just remove the role in the callback

steel slate
#

how do i use a list of ids if those id's aren't in the list do something

naive briar
#

!d in

unkempt canyonBOT
#
in

6.10.2. Membership test operations

The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s. All built-in sequences and set types support this as well as dictionary, for which in tests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y).

For the string and bytes types, x in y is True if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.

naive briar
#

!e

ids = list(range(100))
print(ids)

print(99 in ids)
print(100 in ids)
unkempt canyonBOT
#

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

001 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
002 | True
003 | False
echo wasp
#

ok thanks using MinimalHelpCommand and I can't figure out how to hide a command. How do I do so?

unkempt mauve
#

How do I make the bot only accept button interaction from the interaction user?

slate swan
unkempt mauve
#

thank u

unkempt mauve
fresh ferry
#

how can i fix this

error
, in <module>
    client = discord.Client()
TypeError: __init__() missing 1 required keyword-only argument: 'intents'
source

import os
import googleapiclient.discovery
import discord

intents = discord.Intents.default()
intents.members = True # Enable the Members intent

client = discord.Client(intents=intents)

# Set up Discord client
client = discord.Client()

unkempt mauve
dense coral
frosty parrot
dense coral
#

Yes

#

I can't help you , I'm on the phone now.

frosty parrot
#

ok np

slate swan
naive briar
#

Not really, you can set it by setting the attribute

slate swan
#

so like
button.callback = self.on_button_click ?

naive briar
#

Yup

slate swan
#

awesome.
then how would I be able to pass the name of the button to the interaction?
would that be like button.label = name? then in the on_button_click I'd be able to define it like var = button.label?

naive briar
#

Yes, but you can just set it in the button constructor

slate swan
#

which the button constructor would be the for loop. right?

naive briar
#

Would be in that, yes

#

!d discord.ui.Button

unkempt canyonBOT
#

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

New in version 2.0.
slate swan
#

await interaction.guild.get_channel(voice_channel_id).edit(name=button.label)
AttributeError: 'property' object has no attribute 'get_channel'
but a method would be guild.get_channel to edit a channel name...
cause I see interaction has a guild param, so it should be able to edit it like so... no?

#

also, the docs recommend not using custom_id for conflicts? should i remove it if label is defined?

slate swan
# vocal snow how is `interaction` defined?

interaction=discord.Interaction? i tried interaction:discord.Interaction but it said that
TypeError: ChannelNameView.on_button_click() missing 1 required positional argument: 'interaction'

vocal snow
#

interaction=discord.Interaction is incorrect, that would explain the error

#

can you share the code for on_button_click?

slate swan
vocal snow
#

: is a typehint, = gives it a default value

#

you can remove the typehints entirely if you want

shrewd fjord
#

on_button_click exists on dpy?

slate swan
shrewd fjord
#

I thought of event 💀

slate swan
shrewd fjord
naive briar
#

Oh yeah, that's why you should define it in the init

shrewd fjord
#

Not a button callback

#

Wait nvm exit

slate swan
#

so in the init i should define both?
button=discord.ui.Button
interaction=discord.Interaction

naive briar
#

That's not defining

#

You're creating an alias for a type

slate swan
#

i'm lost now 💀 i thought defining was defining a variable or a def function

naive briar
#

I have a plan

slate swan
#

i'm all eyes and ears >.<

naive briar
#

Uhhhhh

slate swan
#

!d discord.ui.View.interaction_check

unkempt canyonBOT
#

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

A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.

This is useful to override if, for example, you want to ensure that the interaction author is a given user.

The default implementation of this returns `True`.

Note

If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
slate swan
#

this always gets triggered

#

🤷‍♂️ just make use of it

naive briar
#

I wouldn't use that, too much trouble for a simple things

#

I'd do something more simple like

class ViewSubclass(ui.View):
    def __init__(self, ...):
        ...

       for num in range(10):
           btn = ui.Button(...)

           async def acallback(interaction: discord.Interaction):
               # use the btn var that was previously defined
               btn.disabled = True
               ...

           btn.callback = acallback
           self.add_item(btn)

Though this defeats the whole point of subclassing the view and weird looking

slate swan
#

ohhhh. so wait. u can make functions inside for loops?

naive briar
#

I used to do that all the time

slate swan
#

o.o 🤯

naive briar
#

Yeah, works too

fierce haven
#

Hello sory for noob question , how can i run an infinite loop when the bot starts

unkempt canyonBOT
#

examples/background_task.py lines 13 to 25

async def setup_hook(self) -> None:
    # start the task to run in the background
    self.my_background_task.start()

async def on_ready(self):
    print(f'Logged in as {self.user} (ID: {self.user.id})')
    print('------')

@tasks.loop(seconds=60)  # task runs every 60 seconds
async def my_background_task(self):
    channel = self.get_channel(1234567)  # channel ID goes here
    self.counter += 1
    await channel.send(self.counter)```
naive briar
#

I already has a discord.py github tab open, so I just use that

fierce haven
#

thanks alot!

fierce haven
naive briar
#
from discord.ext import tasks

@tasks.loop(seconds=30)
async def atask():
     print("meow")
fierce haven
#

oh thansk!

naive briar
#

Then call the start meth somewhere in an async function

fierce haven
#

start the function?

naive briar
#

!d discord.ext.tasks.Loop.start

unkempt canyonBOT
fierce haven
#

oh okay

#

can i use that in on_ready

naive briar
#

Not preferred, but you can

fierce haven
#

oh okay!

slate swan
#

now i just need to make adjustments so i don't get rate limited... again xD

formal nova
#
@client.command()
async def loop(ctx):
    while True:
        #Stuffs
```When you execute the command 2 times there is 2 instances but is it possible to overwrite like this when you execute one more time it breaks the last command
summer sentinel
#

hi guys, i need my bot sends a message when my activity is playing a current game, how i can do this?👉🏼 👈🏼

slate swan
#

!d discord.ActivityType

unkempt canyonBOT
#

class discord.ActivityType```
Specifies the type of [`Activity`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Activity "discord.Activity"). This is used to check how to interpret the activity itself.
vital glacier
#

Is there a way to make it so if a user leaves a guild (while having the muted role) it'll give it back? So that they stay muted (even if they're tempmuted that it'll remove it after that time even if they left the guild)

Or if the bot restarts that it'll remove the role after a tempmute

gusty flax
#

and u have a time

#

if its a tempmute

vital glacier
#

alright

#

so using db would be the move to go, i figured

gusty flax
#

ye. if u want it to persist, caching wouldnt work

#

besides a remote cache

vital glacier
#

how do u even cache

#

using redis or?

#

Because all I know is that you can cache using redis, but i've never used it and have no idea how it would work

gusty flax
#

there are many methods of caching

#

remote and local

young dagger
#

!e

base_mmr = 1300
num_wins = 14
num_losses = 6
mmr_delta = (num_wins - num_losses) * 25
return base_mmr + mmr_delta```
unkempt canyonBOT
#

@young dagger :x: Your 3.11 eval job has completed with return code 1.

001 |   File "<string>", line 5
002 | SyntaxError: 'return' outside function
vital glacier
#

Is that a database aswell? Or something for a database?

#

Because rn im using psql and asyncpg

gusty flax
vital glacier
#

Yeah that's what I know too

#

but that's ab it

#

guess ill ask my friend for more info and how it works cus he does use redis

gusty flax
young dagger
#

!e

def calculate_mmr(base_mmr, num_wins, num_losses):
    mmr_delta = (num_wins - num_losses) * 25
    return base_mmr + mmr_delta

mmr = calculate_mmr(1300, 14, 6)
print(mmr)```
unkempt canyonBOT
#

@young dagger :white_check_mark: Your 3.11 eval job has completed with return code 0.

1500
sick birch
#

Very fast but limited in capability

#

Perfect for a caching layer

vital glacier
#

Ah good to know

#

Time to figure that out

sick birch
#

Good luck!

vital glacier
#

thanks mate

young dagger
# gusty flax ? do u have a question?

We are currently using a Discord bot that allows people to set up their League account using elo from whatismymmr.com to balance the teams for custom games. However, the website has not been updated for the past 5 months, and we are looking for a new system to determine the elo for each player. How would you determine the elo for each player?

young dagger
gusty flax
slate swan
#

There's a size limit on how large of an integer you can input

tired pollen
#

You can't slash commands does not support them you should use str type

thin raft
#

code?

tired pollen
#

Yep

upbeat otter
#

to save an api request, simply do

user = discord.Object(id=user_id)
await guild.unban(user, ..., ...)
rare echo
delicate flax
#

Hi, when I start my bot on my laptop it works but when I start it on my raspberry pi to keep it online I have this message when I use a command: ```Traceback (most recent call last):
File "/home/#####/.local/lib/python3.9/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self.callback(interaction, **params) # type: ignore
File "/home/#####/edt/emploiDuTemps.py", line 542, in edt
await ctx.response.send_message(embed=m.embed, view=view, ephemeral=True)
File "/home/#####/.local/lib/python3.9/site-packages/discord/interactions.py", line 769, in send_message
await adapter.create_interaction_response(
File "/home/#####/.local/lib/python3.9/site-packages/discord/webhook/async
.py", line 218, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

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

Traceback (most recent call last):
File "/home/#####/.local/lib/python3.9/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/#####/.local/lib/python3.9/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/#####/.local/lib/python3.9/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'edt' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

Did you ever see this error?
slate swan
#

What is a good ping_timeout and interval for the discord gateway because currently it disconnects after every 55.xxx seconds

slate swan
delicate flax
shrewd apex
#

defer it

glad cradle
shrewd apex
#

sup

slate swan
slate swan
#

if it takes longer you need to defer it

delicate flax
sick birch
#

Its not something for you to decide

slate swan
#

Yeah i know but like

slate swan
sick birch
#

It's somewhere around 40-45 seconds

slate swan
#

45

sick birch
#

You should use the interval in the hello payload

#

Instead of just picking some arbitrary one on your own

slate swan
#

what about timeout, just dont set timeout?

delicate flax
slate swan
slate swan
delicate flax
slate swan
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
#

also i only want the command itself

delicate flax
delicate flax
slate swan
delicate flax
#

What defer part?

slate swan
#

you are supposed to defer the interaction

#

so you dont have to respond in 3 seconds

delicate flax
#

I did that but it didn't work

slate swan
#

first of all its not indented into the function body

#

second thing you need to await it

delicate flax
#

I mean with correct indentation

#

I did

#

I mean

#

wait

#

It was more like that

slate swan
#

how about the callback function

#

maybe its all about this one

#

and you need to defer it too

delicate flax
#

but can I send ephemeral message with this?

slate swan
#

yes

delicate flax
#

await ctx.followup.send(embed=m.embed, view=view, ephemeral=True)
Because when I do that it's a regular message not an ephemeral

slate swan
#

yes checked the docs and it can be ephemeral

#

!d discord.Interaction.followup

unkempt canyonBOT
slate swan
#

!d discord.Webhook.send

unkempt canyonBOT
#
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message using the webhook.

The content must be a type that can convert to a string through `str(content)`.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object.

If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects to send.

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

Naming an Interaction object "ctx" isn't the best idea if you want to avoid future confusion in my opinion.
ctx typically represents a commands.Context object, not an Interaction, but of course it's entirely your choice.

delicate flax
#

It was a command context before and I didn't rename the argument

#

🙃

delicate flax
delicate flax
#

That doesn't look like ephemeral 😭

slate swan
delicate flax
#

It's working I had to put it in the defer too

#

Thank you very much, I think it wasn't working because I wanted to do it too quickly so I deleted wrong things

#

But now it works!

vital glacier
#

Is it possible to add a group command into an already existing group command?

slate swan
#

Yes

vital glacier
#

How?

#

@slate swan

slate swan
#
bot.group(pass_context=True)
async def First(ctx):
    if ctx.invoked_subcommand is None:
        await bot.say('Invalid sub command passed...')

@First.group(pass_context=True)
async def Second(ctx):
    if ctx.invoked_subcommand is Second:
        await bot.say('Invalid sub command passed...')

@Second.command(pass_context=True)
async def Third(ctx):
    msg = 'Finally got success {0.author.mention}'.format(ctx.message)
    await bot.say(msg)
``` something Like this
vital glacier
#

ok that worked, but it doesnt appear in my subcmds section in my help cmd embed

shrewd apex
#

!d discord.ext.commands.Group

unkempt canyonBOT
#

class discord.ext.commands.Group(*args, **kwargs)```
A class that implements a grouping protocol for commands to be executed as subcommands.

This class is a subclass of [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") and thus all options valid in [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") are valid in here as well.
shrewd apex
#

the above has a commands property

vital glacier
#

wait ill show u what i mean

#

It shows my sub commands of my group command, right?
But I just made it so that ,role humans remove is a subcommand of ,role humans. Only this subcommand does not show in the subcommands of the role group subcommands

#

so im tryna make it so that it adds ,role humans remove to the subcommands of the Group Command: role embed

shrewd apex
#

dont think it's possible to have subcommand of a subcommand

vital glacier
#

It is tho apparently

cloud dawn
#

Unless that subcommand is also a group then yes.

vital glacier
#

yeah the ,role humans remove is a subcommand of ,role humans

shrewd apex
vital glacier
#

and ,role humans is a group cmd of ,role

cloud dawn
#

For masochists.

shrewd apex
#

lmfao

glad cradle
#

btw FYI no, you can't stack them, it'll Raise a TypeError saying that the callback is already registered

regal cove
smoky sinew
#

!d discord.User.display_avatar

unkempt canyonBOT
#

property display_avatar```
Returns the user’s display avatar.

For regular users this is just their default avatar or uploaded avatar.

New in version 2.0.
regal cove
#

thanks man

#

its fine i fixed it already and forgot to delete my question

smoky sinew
#

the display_avatar is probably closer to what you want since it returns default avatar too

regal cove
#

nah its fine man i fixed it already

fresh ferry
#

this is the error:

line 58, in <module>
    client.loop.create_task(schedule_videos_check())
  File " File ", line 140, in __getattr__
    raise AttributeError(msg)
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook

this is the source im getting my error from

        os.environ['LAST_VIDEO_ID'] = video_id # Update last video ID in environment variable

# Event listener for when bot is ready
@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')
    os.environ['LAST_VIDEO_ID'] = '' # Initialize last video ID as empty string

# Schedule the check_new_videos function to run every 10 minutes
async def schedule_videos_check():
    await client.wait_until_ready()
    while not client.is_closed():
        await check_new_videos()
        await asyncio.sleep(600)

client.loop.create_task(schedule_videos_check()) <------- this is where the error is coming from.

does anyone know the fix

smoky sinew
#

as the error suggests maybe try starting the task in setup_hook instead

young dagger
#

!pastebin

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.

lost lichen
#

im trying to detect a user's rich presence and send them a message if they are playing a game between a range of time

#

currently have this ```py
async def game_detect():
game = None
for activity in disnake.Member.activities:
if isinstance(activity, disnake.Game):
game = activity
print(f'Game detected: {game}')
if game is None:
return print('not playing game')
# if user ID matches '---' and game is being played, send message to user
if game is not None and '---' in game.author.id:
await message.channel.send('Game detected')
return
# We have the return here because we don't want the command to go any further

but I cant figure out how to get the 'author' of the presence, to then send a message to them in DM
slate swan
#

instead of Disnake.Member.activities you need an actual Member object

lost lichen
#

yeah i realise that, i think i got it to work

#

hmm, unrelated issue

#

my token isnt valid but i just regnerated it

#

it has a different format than before

#

some previously generated tokens all started with NjExMzAz.. whearas now it starts with ODkwNDA..

#

did discord update their token generation format??

fresh ferry
#

anyone know why i cant gen a url for my bot in the dev portal /

naive briar
lost lichen
#

can I just, not use my bot now?

#

im so confused its the right token in the right string format no trailing whitespace

naive briar
#

Discord changing token format is not a big deal

lost lichen
#

doesn't that break all new bots though

naive briar
#

No

lost lichen
#

ok, cool, then why do i get this error if the token is 'valid'?

naive briar
#

You entered it wrong